package com.thinkTank.oa.controller;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import com.thinkTank.oa.common.Constant;
import com.thinkTank.oa.common.SystemGlobals;
import com.thinkTank.oa.configuration.Log;
import com.thinkTank.oa.configuration.RefPid;
import com.thinkTank.oa.entity.ButtDetails;
import com.thinkTank.oa.entity.ConfOfAttr;
import com.thinkTank.oa.entity.Conference;
import com.thinkTank.oa.entity.Customer;
import com.thinkTank.oa.entity.Demand;
import com.thinkTank.oa.entity.Dictiontry;
import com.thinkTank.oa.entity.Person;
import com.thinkTank.oa.entity.Project;
import com.thinkTank.oa.entity.ProjectOfPerson;
import com.thinkTank.oa.entity.Subscribe;
import com.thinkTank.oa.entity.User;
import com.thinkTank.oa.entity.UserDownPerson;
import com.thinkTank.oa.lucene.IsolrOperation;
import com.thinkTank.oa.lucene.LuceneDemand;
import com.thinkTank.oa.lucene.LucenePerson;
import com.thinkTank.oa.lucene.Pagination;
import com.thinkTank.oa.lucene.SolrOperation;
import com.thinkTank.oa.service.ConOfAttrService;
import com.thinkTank.oa.service.ConferenceService;
import com.thinkTank.oa.service.CustomerService;
import com.thinkTank.oa.service.DemandService;
import com.thinkTank.oa.service.DetailsService;
import com.thinkTank.oa.service.DictiontryService;
import com.thinkTank.oa.service.PersonService;
import com.thinkTank.oa.service.ProjectOfPersonService;
import com.thinkTank.oa.service.ProjectService;
import com.thinkTank.oa.service.SubscribeService;
import com.thinkTank.oa.service.UserDownPersonService;
import com.thinkTank.oa.service.UserLookService;
import com.thinkTank.oa.service.UserService;
import com.thinkTank.oa.util.ExcelUtil;
import com.thinkTank.oa.util.FileUtils;
import com.thinkTank.oa.util.Json;
import com.thinkTank.oa.util.StrUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 专家controller
 * @author 董力
 * 2018-8-9
 */
@Controller
@RequestMapping("person")
public class PersonController extends BaseController{

    /* 日志输出 */
    private final Logger logger = LoggerFactory.getLogger(PersonController.class);

    @Resource 
    private PersonService personService; 		 //专家
    @Resource
    private DictiontryService dictiontryService; //字典
    @Resource
    private ConferenceService conferenceService; //会议
    @Resource
    private DetailsService detailsService;       //详情
    @Resource
    private DemandService demandService;		 //需求
    @Resource
    private UserService userService;			 //用户
    @Resource
    private ConOfAttrService conOfAttrService;   //会议相关
    @Resource
  	private CustomerService customerService;     //客户
    @Resource
    private ProjectService projectService;       //项目
    @Resource
    private SubscribeService subscribeService;   //关注
    @Resource
    private ProjectOfPersonService projectOfPersonService;   //项目持有人中间表
    @Resource
    private UserDownPersonService userDownPersonService;   //用户下载专家表
    
    @Resource
    private UserLookService userLookService;
    
    /**将常用的list封装到Model中*/
    private void addListToModel(Model model){
    	/**
    	 * 用于修改页面的回显
    	 */
    	//项目来源
        List<Dictiontry> projecSourcetDictiontryList = getProjectSorce();
        //所有国家
        List<Dictiontry> countryDictiontryList = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_COUNTRY);
        //所有省份
        List<Dictiontry> provinceDictiontryList = getAreaProvince();
        //所属领域
        List<Dictiontry> researchFieldDictiontryList = getResearchField();
        //专家类型
        List<Dictiontry> personTypeList = getPersonType();
        //人才级别
        List<Dictiontry> talentLevelListByDic = getTalentLevel();
		/**
		 * 用于显示对接详情添加页面的遍历
		 */
		//对接状态下拉列表
		List<Dictiontry> buttStatus = getButtStatus();
		/**
		 * 匹配需求
		 */
		// 需求类型demandType
        List<Dictiontry> demandTypeDictiontryList = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_DEMANDTYPE);
        // 需求状态
        List<Dictiontry> demandStatusDictiontryList = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_DEMANDSTATUS);
        // 专家类型
        List<Dictiontry> personTypeDictiontryList = getPersonType();
        // 人才级别
        List<Dictiontry> talentLevelDictiontryList = getTalentLevel();
        // 专家离退休状态
        List<Dictiontry> personRetireDictiontryList = getDicList(Constant.DICTIONTRY_PERSONRETIRE);

        model.addAttribute("projecSourcetDictiontryList", projecSourcetDictiontryList);
        model.addAttribute("provinceDictiontryList", provinceDictiontryList);
        model.addAttribute("researchFieldDictiontryList", researchFieldDictiontryList);
        model.addAttribute("personTypeList", personTypeList);
        model.addAttribute("talentLevelListByDic", talentLevelListByDic);
        model.addAttribute("buttStatus", buttStatus);
        model.addAttribute("countryDictiontryList",countryDictiontryList );
        model.addAttribute("demandTypeDictiontryList",demandTypeDictiontryList );
        model.addAttribute("demandStatusDictiontryList",demandStatusDictiontryList );
        model.addAttribute("personTypeDictiontryList",personTypeDictiontryList );
        model.addAttribute("talentLevelDictiontryList",talentLevelDictiontryList );
        model.addAttribute("personRetireDictiontryList",personRetireDictiontryList );
    }
    
    /**
	 * 分页查询
	 * @return 返回专家主页面
	 */
	@RequestMapping(value= "findPersonList",produces="application/json;charset=UTF-8")
	public String findPersonList(Integer pageNo,Person person,Model model,
			@RequestParam(value = "expertNumberId", required = false) String expertNumberId,HttpServletRequest request
			){
		//分页
		if(null==pageNo){
			pageNo=1;
		}
		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);
		
		//'E'+专家id来检索专家时，去除前缀操作
		String expertNum = "";
		// 重新复制客户id
		if (StringUtil.isNotEmpty(expertNumberId)) {
			expertNum = String.valueOf(expertNumberId.trim());
			// 去除字母
			expertNum = expertNum.replaceAll("[a-zA-Z]", "");
		}
		if (StringUtil.isNotEmpty(expertNum)) {
			person.setExpertNumber(Integer.parseInt(expertNum));
		}
        if (person.getTalentLevel() != null) {
        	String[] talentLevelArr = person.getTalentLevel().split(",");
        	person.setTalentLevelNumber(talentLevelArr.length);
        	person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
        	model.addAttribute("talentLevelArr",talentLevelArr );
        }else {
        	model.addAttribute("talentLevelArr","" );
		}
        String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(person.getResearchField())) {
			researchFieldArr = person.getResearchField().split(",");
			person.setResearchFieldNumber(researchFieldArr.length);
			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		}
		
		//人才级别
        List<Dictiontry> talentLevelListByDic = getTalentLevel();		
        if (StrUtil.isEmpty(person)) {
        	List<String> typeWorthList = Arrays.asList("需求联系人", "客户联系人", "项目联系人");
        	List<Integer> typeList = getDicList(Constant.DICTIONTRY_PERSONTYPE).stream()
        			.filter(dic -> !typeWorthList.contains(dic.getWorth()))
        			.map(Dictiontry::getPid).collect(Collectors.toList());
        	person.setTypeList(typeList);
        }
		//模糊查询person表
		List<Person> list = personService.findMPersonList(person);
		//将list放进PageInfo
		PageInfo<Person> pageInfo = new PageInfo<Person>(list);
		//因为人才级别属非必填字段但是页面要展示该字段 ，所以在这里先判断是否为空然后进行遍历
		pageInfo.getList().stream().filter(per -> StringUtil.isNotEmpty(per.getTalentLevel()))
						.forEach(per -> per.setTalentLevel(getDictiontryWorth(per.getTalentLevel(), talentLevelListByDic)));
		//遍历专家类型
		pageInfo.getList().stream().forEach(per -> per.setTypeWorth(getDicSingleWorth(per.getType(), Constant.DICTIONTRY_PERSONTYPE)));
		//录入人姓名
		pageInfo.getList().stream().forEach(per -> per.setCollectPersonName(userService.getById(per.getCollectPersonId()).getFullName()));
		
		if (person.getArea() != null){
            areaModel(model, person.getArea(), person.getDomesticOrForeign());
		}
		
		/**
		 * 查询已关注
		 */
		Subscribe subscribe = new Subscribe(); //实体类
		subscribe.setSubType(4); //4代表是专家
		subscribe.setUserid(getUserId(request)); //获取用户
		List<Subscribe> subList = subscribeService.queryAll(subscribe);
		List<String> subPersonIdList = subList.stream().map(Subscribe::getTypeObject).collect(Collectors.toList());
		model.addAttribute("subPersonIdList", subPersonIdList);
		
		addListToModel(model);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("person", person);
		model.addAttribute("researchFieldArr",researchFieldArr );
		model.addAttribute("talentLevelListByDic",talentLevelListByDic );
		
		return "person/person";
	}
	
	/**
	 * 用户查看本人录入的数据
	 * @author dongli
	 * @date 2018年11月8日
	 * @return
	 */
	@RequestMapping(value= "showSelf",produces="application/json;charset=UTF-8")
	public String showSelf(Integer pageNo,Person person,Model model,
			@RequestParam(value = "expertNumberId", required = false) String expertNumberId,HttpServletRequest request
			){
		//分页
		if(null==pageNo){
			pageNo=1;
		}
		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);
		
		//'E'+专家id来检索专家时，去除前缀操作
		String expertNum = "";
		// 重新复制客户id
		if (StringUtil.isNotEmpty(expertNumberId)) {
			expertNum = String.valueOf(expertNumberId.trim());
			// 去除字母
			expertNum = expertNum.replaceAll("[a-zA-Z]", "");
		}
		if (StringUtil.isNotEmpty(expertNum)) {
			person.setExpertNumber(Integer.parseInt(expertNum));
		}
        if (person.getTalentLevel() != null) {
        	String[] talentLevelArr = person.getTalentLevel().split(",");
        	person.setTalentLevelNumber(talentLevelArr.length);
        	person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
        	model.addAttribute("talentLevelArr",talentLevelArr );
        }else {
        	model.addAttribute("talentLevelArr","" );
		}
        String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(person.getResearchField())) {
			researchFieldArr = person.getResearchField().split(",");
			person.setResearchFieldNumber(researchFieldArr.length);
			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		}
		
		//从session中获取收集人（录入人）登录账号，存放在person中
		person.setCollectPersonId(getUserId(request));
		
		//人才级别
        List<Dictiontry> talentLevelListByDic = getTalentLevel();		
		//模糊查询person表
		List<Person> list = personService.findMPersonList(person);
		//将list放进PageInfo
		PageInfo<Person> pageInfo = new PageInfo<Person>(list);
		//因为人才级别属非必填字段但是页面要展示该字段 ，所以在这里先判断是否为空然后进行遍历
		pageInfo.getList().stream().filter(per -> StringUtil.isNotEmpty(per.getTalentLevel()))
						.forEach(per -> per.setTalentLevel(getDictiontryWorth(per.getTalentLevel(), talentLevelListByDic)));
		//遍历专家类型
		pageInfo.getList().stream().forEach(per -> per.setTypeWorth(getDicSingleWorth(per.getType(), Constant.DICTIONTRY_PERSONTYPE)));
		//录入人姓名
		pageInfo.getList().stream().forEach(per -> per.setCollectPersonName(userService.getById(per.getCollectPersonId()).getFullName()));
		
		if (person.getArea() != null){
            areaModel(model, person.getArea(), person.getDomesticOrForeign());
		}
		
		/**
		 * 查询已关注
		 */
		Subscribe subscribe = new Subscribe(); //实体类
		subscribe.setSubType(4); //4代表是专家
		subscribe.setUserid(getUserId(request)); //获取用户
		List<Subscribe> subList = subscribeService.queryAll(subscribe);
		List<String> subPersonIdList = subList.stream().map(Subscribe::getTypeObject).collect(Collectors.toList());
		model.addAttribute("subPersonIdList", subPersonIdList);
		
		addListToModel(model);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("person", person);
		model.addAttribute("researchFieldArr",researchFieldArr );
		model.addAttribute("talentLevelListByDic",talentLevelListByDic );
		
		return "person/personBySelf";
	}
	
	/**
	 * 批量关注
	 * @author dongli
	 * @date 2018年10月24日
	 * @param objectType
	 * @param type
	 * @param request
	 * @return
	 */
	@RequestMapping(value="addSubscribe")
	@ResponseBody
	public Json addSubscribe(String objectType,Integer type,HttpServletRequest request) {
		try{
			Subscribe sub = subscribeService.findSubByUserIdAndType(this.getUserId(request), objectType,type);
			if(null!=sub){
				return new Json(false, "success", "您已经关注,请不要重复关注！");
			}else{
				 sub = new Subscribe();
				 sub.setPid(StrUtil.getUUID32());
				 sub.setSubType(4);
				 sub.setUserid(this.getUserId(request));
				 sub.setTypeObject(objectType);
				 sub.setAddTime(StrUtil.getCurrentDateTime());
				 sub.setRemark1(personService.getById(objectType).getName());
				 
				 subscribeService.add(sub);
			}
			return new Json(true, "success", "批量关注成功！");
		}catch(Exception e){
			return new Json(false, "fail", "关注失败,请联系管理员！");
		}
	}
	
	/**
	 * 进入隐藏的专家管理页面
	 * @author dongli
	 * @date 2018年9月6日
	 * @param person
	 * @param model
	 * @return
	 */
	@RequestMapping(value= "personHideList",produces="application/json;charset=UTF-8")
	public String personHideList(Person person,Model model){
		
		PageInfo<Person> pageInfo = new PageInfo<Person>(new ArrayList<>());
		
		addListToModel(model);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("person", person);
		return "person/person_hide";
	}
	
	/**
	 * 分页查询隐藏的专家管理页面
	 * @author dongli
	 * @date 2018年8月28日
	 * @param pageNo
	 * @param person
	 * @param model
	 * @param expertNumberId
	 * @return
	 */
	@RequestMapping(value= "findPersonHideList",produces="application/json;charset=UTF-8")
	public String findPersonHideList(Model model,@RequestParam(defaultValue = "1") int pageNo,Person person,
			@RequestParam(value = "expertNumberId", required = false) String expertNumberId,HttpServletRequest request
			){
		if (StrUtil.isEmpty(person)) {
            model.addAttribute("searchEmpty", "至少需要一个搜索条件");
            return personHideList(person,model);
        }
		
		//分页
		PageHelper.startPage(pageNo, DEFAULT_COUNT);
		
		//'E'+专家id来检索专家时，去除前缀操作
		String expertNum = "";
		// 重新复制客户id
		if (StringUtil.isNotEmpty(expertNumberId)) {
			expertNum = String.valueOf(expertNumberId.trim());
			// 去除字母
			expertNum = expertNum.replaceAll("[a-zA-Z]", "");
		}
		if (StringUtil.isNotEmpty(expertNum)) {
			person.setExpertNumber(Integer.parseInt(expertNum));
		}
		if (person.getTalentLevel() != null) {
        	String[] talentLevelArr = person.getTalentLevel().split(",");
        	person.setTalentLevelNumber(talentLevelArr.length);
        	person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
        	model.addAttribute("talentLevelArr",talentLevelArr );
        }else {
        	model.addAttribute("talentLevelArr","" );
		}
		
		String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(person.getResearchField())) {
			researchFieldArr = person.getResearchField().split(",");
			person.setResearchFieldNumber(researchFieldArr.length);
			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		}
		
		//人才级别
        List<Dictiontry> talentLevelListByDic = getTalentLevel();
		//模糊查询person表
		List<Person> list = personService.findMPersonList(person);
		//将list放进PageInfo
		PageInfo<Person> pageInfo = new PageInfo<Person>(list);
		//因为人才级别属非必填字段但是页面要展示该字段 ，所以在这里先判断是否为空然后进行遍历
		pageInfo.getList().stream().filter(per -> StringUtil.isNotEmpty(per.getTalentLevel()))
						.forEach(per -> per.setTalentLevel(getDictiontryWorth(per.getTalentLevel(), talentLevelListByDic)));
		//遍历专家类型
		pageInfo.getList().stream().forEach(per -> per.setTypeWorth(getDicSingleWorth(per.getType(), Constant.DICTIONTRY_PERSONTYPE)));
		//录入人姓名
		pageInfo.getList().stream().forEach(per -> per.setCollectPersonName(userService.getById(per.getCollectPersonId()).getFullName()));
		
		if (person.getArea() != null){
            areaModel(model, person.getArea(), person.getDomesticOrForeign());
		}
		
		/**
		 * 查询已关注
		 */
		Subscribe subscribe = new Subscribe(); //实体类
		subscribe.setSubType(4); //4代表是专家
		subscribe.setUserid(getUserId(request)); //获取用户
		List<Subscribe> subList = subscribeService.queryAll(subscribe);
		List<String> subPersonIdList = subList.stream().map(Subscribe::getTypeObject).collect(Collectors.toList());
		model.addAttribute("subPersonIdList", subPersonIdList);
		
		addListToModel(model);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("person", person);
		model.addAttribute("researchFieldArr",researchFieldArr );
		model.addAttribute("talentLevelListByDic",talentLevelListByDic );
		
		return "person/person_hide";
	}
	
	/**
	 * 把Person转换为LucenePerson
	 * @author dongli
	 * @date 2018年9月21日
	 * @param person
	 * @return
	 */
	public LucenePerson lucenePersonConversion(Person person){
		LucenePerson lp = new LucenePerson();
		try{
			//pid
			String expertId = person.getPid();
			if(expertId!=null&&!"".equals(expertId)){
				lp.setExpertId(expertId);
			}
			//专家id
			Integer expertNumber = person.getExpertNumber();
			if(expertNumber!=null&&expertNumber>0){
				lp.setExpertNumber("E"+expertNumber);
			}
			//专家来源
			Integer source = person.getSource();
			if(source!=null&&source>0){
				lp.setSource(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
			}
			//专家类型
			Integer type = person.getType();
			if(type!=null && type>0){
				lp.setType(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
			}
			/**
			 * 所属领域
			 */
			String researchField = person.getResearchField();
			if(researchField!=null &&!"".equals(researchField)){
				researchField = getDicCheckboxWorth(person.getResearchFieldInteger().toString(), Constant.DICTIONTRY_PROJECTFIELD);
				String[] arr  = researchField.split(",");
				List<String> list = new ArrayList<String>();
				for(String t :arr){
					list.add(t);
				}
				lp.setResearchField(list);
			}
			//地区
			String	area =person.getArea();
			if(area!=null&&!"".equals(area)){
				lp.setArea(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
			}
			/**
			 * 人才级别
			 */
			String	talentLevel =person.getTalentLevel();
			if(talentLevel!=null&&!"".equals(talentLevel)){
				talentLevel = getDicCheckboxWorth(person.getTalentLevelInteger().toString(), Constant.DICTIONTRY_TALENTLEVEL);
				String[] arr  = talentLevel.split(",");
				List<String> list = new ArrayList<String>();
				for(String t :arr){
					list.add(t);
				}
				lp.setTalentLevel(list);
			}
			//姓名
			String	name = person.getName();
			if(name!=null&&!"".equals(name)){
				lp.setName(name);
			}
			//毕业院校及所学专业
			String	schoolAndMajor =person.getSchoolAndMajor();
			if(schoolAndMajor!=null&&!"".equals(schoolAndMajor)){
				lp.setSchoolAndMajor(schoolAndMajor);
			}
			//单位
			String	unit = person.getUnit();
			if(unit!=null&&!"".equals(unit)){
				lp.setUnit(unit);
			}
			//职务(职称)
			String	title = person.getTitle();
			if(title!=null&&!"".equals(title)){
				lp.setTitle(title);
			}
			//专业领域
			String	professionaField =person.getProfessionaField();
			if(professionaField!=null&&!"".equals(professionaField)){
				lp.setProfessionaField(professionaField);
			}
			//教育背景
			String	education =person.getEducation();
			if(education!=null&&!"".equals(education)){
				lp.setEducation(education);
			}
			//工作经历
			String	workExp =person.getWorkExp();
			if(workExp!=null&&!"".equals(workExp)){
				lp.setWorkExp(workExp);
			}
			//荣誉奖励
			String	honorAward =person.getHonorAward();
			if(honorAward!=null&&!"".equals(honorAward)){
				lp.setHonorAward(honorAward);
			}
			//科技成果
			String	technica = person.getTechnica();
			if(technica!=null&&!"".equals(technica)){
				lp.setTechnica(technica);
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		return lp;
	}
	
	/**
	 * 进入添加页面
	 * @return
	 */
	@RequestMapping(value= "addView",produces="application/json;charset=UTF-8")
	public String addView(Model model){
		//将person传递给前台
		if(!model.containsAttribute("person")){
			model.addAttribute("person", new Person());
		}
		if (!model.containsAttribute("researchFieldArr")) {
			model.addAttribute("researchFieldArr", "");
		}
		if (!model.containsAttribute("talentLevelArr")) {
			model.addAttribute("talentLevelArr", "");
		}
				
		//调用本类方法
		addListToModel(model);
		return "person/personAdd";
	}
	
	//提取添加页面回显的公共方法
	public void addInfo(Person person,Model model){
		// 获取地区相关数据，便于回显
		String areaId = person.getArea();
		String cityId = "";
		String province = "";
		if (StringUtil.isNotEmpty(areaId)) {
			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
				// 说明是区的id
				// 截取得到省和市的id
				cityId = areaId.substring(0, 5);
				province = areaId.substring(0, 2);
				model.addAttribute("areaId", areaId);
				model.addAttribute("cityId", cityId);
				model.addAttribute("province", province);
			}
			if (areaId.length() < 3 && areaId.length() > 0) {
				// 说明是省的id
				model.addAttribute("province", areaId);
			}
			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
				// 说明是市的id
				// 截取得到省和市的id
				cityId = areaId;
				province = areaId.substring(0, 2);
				model.addAttribute("province", province);
				model.addAttribute("cityId", cityId);
			}

			// 所有市
			List<Dictiontry> cityDictiontryList = getCityByProvince(province);
			// 所有区
			List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);

			model.addAttribute("cityDictiontryList", cityDictiontryList);
			model.addAttribute("areaDictiontryList", areaDictiontryList);
		}

		//回显所属领域
		String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(person.getResearchField())) {
			researchFieldArr = person.getResearchField().split(",");
		}
		if (researchFieldArr != null) {
			model.addAttribute("researchFieldArr", researchFieldArr);
		} else {
			model.addAttribute("researchFieldArr", "");
		}
		//回显人才级别
		String[] talentLevelArr = null;
		if (StringUtil.isNotEmpty(person.getTalentLevel())) {
			talentLevelArr = person.getTalentLevel().split(",");
		}
		if (talentLevelArr != null) {
			model.addAttribute("talentLevelArr", talentLevelArr);
		} else {
			model.addAttribute("talentLevelArr", "");
		}

		if(person.getDomesticOrForeign()!=null){
			//国内外和省市区、国家名都不能为空
			if (person.getDomesticOrForeign() == 1 && areaId != null) {
				model.addAttribute("countryId", Integer.parseInt(areaId));
			}
		}
		
	}
	
	/**
	 * 展示通过专家姓名查询出来的专家列表弹框
	 * @author dongli
	 * @date 2018年10月29日
	 * @param personName
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "showselectperson")
	public String showselectperson(@RequestParam(value = "personName", required = false) String personName,Model model,HttpServletRequest request) {
		
		Person person=new Person();
		person.setName(personName);
		//通过姓名查询专家
		List<Person> personList = personService.findMPersonList(person);
		//如果数据库中没有此人返回“noResult”
		if(personList.size()<1){
			return "testshowselectperson";
		}
		model.addAttribute("personList", personList);
		//返回一个用来展示查询出来的专家列表弹框
		return "showselectperson";
	}
	
	/**
	 * 在弹框中通过专家pid查询专家
	 * @author dongli
	 * @date 2018年10月29日
	 * @param checkStr
	 * @param customerId
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "returnCheckperson", method = RequestMethod.GET)
	@ResponseBody
	public Person returnCheckperson(@RequestParam(value = "checkStr", required = false) String checkStr, Model model,HttpServletRequest request) {
		//通过专家pid查询专家，返回专家实体类
		Person person=personService.findPersonByPid(checkStr);
		return person;
	}
	
	/**
	 * 在弹框中选中的专家将其信息回显在专家添加页面
	 * @author dongli
	 * @date 2018年10月29日
	 * @param pid
	 * @param model
	 * @param personId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "addSelectView")
	public String addCustomerContact(Model model, @RequestParam(value = "personId") String personId,HttpServletRequest request) {

		//调用本类方法
		addListToModel(model);
		
		//通过pid查询专家表
		Person person = personService.findPersonByPid(personId);
		
		String cityId = "";
		String province = "";
		String areaId = String.valueOf(person.getArea());
		if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
			// 说明是区的id
			// 截取得到省和市的id
			cityId = areaId.substring(0, 5);
			province = areaId.substring(0, 2);
			model.addAttribute("areaId", areaId);
			model.addAttribute("cityId", cityId);
			model.addAttribute("province", province);
		}
		if (areaId.length() < 3 && areaId.length() > 0) {
			// 说明是省的id
			model.addAttribute("province", areaId);
		}
		if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
			// 说明是市的id
			// 截取得到省和市的id
			cityId = areaId;
			province = areaId.substring(0, 2);
			model.addAttribute("province", province);
			model.addAttribute("cityId", cityId);
		}

		if (person.getDomesticOrForeign() == 1) {
			model.addAttribute("countryId", Integer.parseInt(areaId));
		}
		
		// 所有省份
		List<Dictiontry> provinceDictiontryList = getAreaProvince();
		// 所有市
		List<Dictiontry> cityDictiontryList = getCityByProvince(province);
		// 所有区
		List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);
		
		// 所属领域二进制转化为字符串并存放到数组中
		String[] researchFieldArr = StrUtil.byteToString(person.getResearchField()).split(",");
		model.addAttribute("researchFieldArr", researchFieldArr);
		// 人才级别二进制转化为字符串并存放到数组中
		if (person.getTalentLevel() != null) {
			String[] talentLevelFieldArr = StrUtil.byteToString(person.getTalentLevel()).split(",");
			model.addAttribute("talentLevelFieldArr", talentLevelFieldArr);
		}else {
			model.addAttribute("talentLevelFieldArr", "");
		}
		
		model.addAttribute("person",person);
		model.addAttribute("provinceDictiontryList", provinceDictiontryList);
		model.addAttribute("cityDictiontryList", cityDictiontryList);
		model.addAttribute("areaDictiontryList", areaDictiontryList);

		//点击修改后进入修改页面（原因：添加页面里有重名验证）
		return "person/personUpdate";
	}
	
	/**
	 * 添加方法
	 * @param person 
	 * @return 专家的主页面
	 * @throws IOException 
	 */
	@RequestMapping(value= "addPerson",method = RequestMethod.POST)
	public String addPerson(@Valid Person person,BindingResult result,@RequestParam("annex1") MultipartFile annex1,
			HttpServletRequest request,Model model) throws Exception{
		//pid
		person.setPid(StrUtil.getUUID32());
		//收集人（录入人）
		person.setCollectPersonId(getUserInfoBySession(request).getUserId());
		//录入时间
		person.setEntryTime(StrUtil.getCurrentDateTime());
		//将所属领域复选框转换为二进制格式
		if(StringUtil.isNotEmpty(person.getResearchField())){
			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		}
		//将人才级别复选框转换为二进制格式
		if(StringUtil.isNotEmpty(person.getTalentLevel())){
			person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
		}
		
		//上传附件
		if (!annex1.isEmpty() && annex1 != null) {
			// 文件名字
			String fileName = annex1.getOriginalFilename();
			String oldFileName = FileUtils.generateFileName("person", fileName);
			person.setAnnex(oldFileName);
			try {
				FileUtils.uploadFile(annex1.getBytes(), Constant.DEF_PERSON_PATH, oldFileName);
			} catch (Exception e) {
				logger.error("上传文件失败：" + e.getMessage());
			}
		}
		
		// 表单验证逻辑
		if (result.hasErrors()) {
			List<FieldError> fieldErrors = result.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				//调用本类方法
				addInfo(person,model);
				
				//发生错误，直接return
				model.addAttribute("person", person);
				return addView(model);
			}
		}
		
		//专家入库条件:姓名+（固定电话、手机、邮箱、微信、其他联系方式）五种联系方式中的其中一种才可以入库
		if (!person.getName().isEmpty() && (!person.getTell().isEmpty() || !person.getFixedPhone().isEmpty() || 
			!person.getEmail().isEmpty() || !person.getWechat().isEmpty() || !person.getOtherContact().isEmpty())
		){
			//当数据库中可以通过姓名+任意一种联系方式查询出专家 就提示此人已存在
			Person per = personService.findPersonByInfo(person);
			if (per != null) {
				model.addAttribute("info", "此人已存在！");
				//调用本类方法
				addInfo(person,model);
				
				model.addAttribute("person", person);
				return addView(model);
			}
			personService.addPerson(person);
			
			/**
			 * 更新索引
			 */
			//对象复制 person ==> lucenePerson
			//BeanUtils.copyProperties(person, lucenePerson);
			//创建isolrOperation接口对象指向其实现类 
			IsolrOperation<LucenePerson> isolrOperation = new SolrOperation<LucenePerson>();
			//把Person转换为LucenePerson
			LucenePerson lucenePerson = lucenePersonConversion(person);
			if(lucenePerson==null){
				logger.error("添加索引失败!!!!");
				logger.error(person.toString());
			}
			List<LucenePerson> list = new ArrayList<LucenePerson>();
			list.add(lucenePerson);
			isolrOperation.add("person", list);
			
		}else {
			model.addAttribute("alert", "请至少填写一种联系方式！");
			//调用本类方法
			addInfo(person,model);
			
			model.addAttribute("person", person);
			return addView(model);
		}
		
		//通过重定向返回专家页面
		return "redirect:/person/findPersonList";
	}
	
	/**
	 * 进入修改页面
	 * @return
	 */
	@RequestMapping(value= "updateView",produces="application/json;charset=UTF-8")
	public String updateView(@RequestParam("pid") String pid,Model model,@RequestParam(value = "origType", required = false) String origType,@RequestParam(value = "conferencePid", required = false) String conferencePid){
		//调用本类方法
		addListToModel(model);
		
		//通过pid查询专家表
		Person person = personService.findPersonByPid(pid);
		
		String cityId = "";
		String province = "";
		String areaId = String.valueOf(person.getArea());
		if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
			// 说明是区的id
			// 截取得到省和市的id
			cityId = areaId.substring(0, 5);
			province = areaId.substring(0, 2);
			model.addAttribute("areaId", areaId);
			model.addAttribute("cityId", cityId);
			model.addAttribute("province", province);
		}
		if (areaId.length() < 3 && areaId.length() > 0) {
			// 说明是省的id
			model.addAttribute("province", areaId);
		}
		if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
			// 说明是市的id
			// 截取得到省和市的id
			cityId = areaId;
			province = areaId.substring(0, 2);
			model.addAttribute("province", province);
			model.addAttribute("cityId", cityId);
		}

		if (person.getDomesticOrForeign() == 1) {
			model.addAttribute("countryId", Integer.parseInt(areaId));
		}
		
		// 所有省份
		List<Dictiontry> provinceDictiontryList = getAreaProvince();
		// 所有市
		List<Dictiontry> cityDictiontryList = getCityByProvince(province);
		// 所有区
		List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);
		
		// 所属领域二进制转化为字符串并存放到数组中
		String[] researchFieldArr = StrUtil.byteToString(person.getResearchField()).split(",");
		model.addAttribute("researchFieldArr", researchFieldArr);
		// 人才级别二进制转化为字符串并存放到数组中
		if (person.getTalentLevel() != null) {
			String[] talentLevelFieldArr = StrUtil.byteToString(person.getTalentLevel()).split(",");
			model.addAttribute("talentLevelFieldArr", talentLevelFieldArr);
		}else {
			model.addAttribute("talentLevelFieldArr", "");
		}
		
		model.addAttribute("person",person);
		model.addAttribute("provinceDictiontryList", provinceDictiontryList);
		model.addAttribute("cityDictiontryList", cityDictiontryList);
		model.addAttribute("areaDictiontryList", areaDictiontryList);
		
		model.addAttribute("origType", origType);
		model.addAttribute("conferencePid", conferencePid);
		
		return "person/personUpdate";
	}
	
	/**
	 * 修改方法
	 * @return
	 */
	@Log("修改专家")
	@RequestMapping(value= "updatePerson",produces="application/json;charset=UTF-8",method = RequestMethod.POST)
	public String updatePerson(@RefPid @Valid Person person,BindingResult bindingResult,@RequestParam("annex1") MultipartFile annex1,
			HttpServletRequest req,Model model,@RequestParam(value = "origType", required = false) String origType,@RequestParam(value = "conferencePid", required = false) String conferencePid,@RequestParam(value = "customerId", required = false) String customerId){
		//重新选择附件并上传
		if (!annex1.isEmpty() && annex1 != null) {
			// 文件名字
			String fileName = annex1.getOriginalFilename();
			String oldFileName = FileUtils.generateFileName("person", fileName);
			person.setAnnex(oldFileName);
			try {
				FileUtils.uploadFile(annex1.getBytes(), Constant.DEF_PERSON_PATH, oldFileName);
			} catch (Exception e) {
				logger.error("上传文件失败：" + e.getMessage());
			}
		}else {
			//当附件为空的时候不改变原来附件的内容
			String fileName = FileUtils.transferTo(Constant.DEF_PERSON_PATH, annex1, "person");
			Person per = personService.getById(person.getPid());
			fileName = StringUtil.isEmpty(fileName) ? per.getAnnex() : fileName ;
			person.setAnnex(fileName);
		}
		
		//表单验证逻辑
		if (bindingResult.hasErrors()) {
			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
			for (FieldError fieldError : fieldErrors) {
				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
				// 发生错误，直接return
				model.addAttribute("person", person);
				return updateView(person.getPid(),model,null,null);
			}
		}
		
		//设置最新更新时间
		person.setUpdateTime(StrUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
		
		//判断联系方式是否有改变，如果没有就将原来的值赋给它
		Person per2 = personService.getById(person.getPid());
		String fixedPhone = person.getFixedPhone();  //固定电话
		String tell = person.getTell();  //手机
		String email = person.getEmail();  //邮箱
		String wechat = person.getWechat();  //微信
		String otherContact = person.getOtherContact();  //其他联系方式
		if (StringUtil.isNotEmpty(fixedPhone) && fixedPhone.contains("*")) {
			person.setFixedPhone(per2.getFixedPhone());
		}
		if (StringUtil.isNotEmpty(tell) && tell.contains("*")) {
			person.setTell(per2.getTell());
		}
		if (StringUtil.isNotEmpty(email) && email.contains("*")) {
			person.setEmail(per2.getEmail());
		}
		if (StringUtil.isNotEmpty(wechat) && wechat.contains("*")) {
			person.setWechat(per2.getWechat());
		}
		if (StringUtil.isNotEmpty(otherContact) && otherContact.contains("*")) {
			person.setOtherContact(per2.getOtherContact());
		}
		
		// 转化为二进制保存
		person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		if (person.getTalentLevel() != null) {
			person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
		}
		
		//专家入库条件:姓名+（固定电话、手机、邮箱、微信、其他联系方式）五种联系方式中的其中一种才可以入库
		if (!hasContact(person)) {
            model.addAttribute("alert", "至少填写一种联系方式");
            return updateView(person.getPid(),model,null,null);
        } 
//		else if (personService.updatePersonExists(person)) {
//        	model.addAttribute("info", "不能修改为已存在的专家");
//        	return updateView(person.getPid(),model,null,null);
//        }
		personService.update(person);
		
		/**
		 * 更新索引
		 */
		//创建isolrOperation接口对象指向其实现类 
		IsolrOperation<LucenePerson> isolrOperation = new SolrOperation<LucenePerson>();
		//把Person转换为LucenePerson
		LucenePerson lucenePerson = lucenePersonConversion(person);
		isolrOperation.update("person", lucenePerson);
		
		//调用本类方法
		addListToModel(model);
		
		//跳转页面
		if("333".equals(origType) && StringUtil.isNotEmpty(customerId)){
			return "redirect:/customer/customerList";
		}else if(StringUtil.isNotEmpty(customerId) && "222".equals(origType)){
			return "redirect:/customer/showDetail?customerId=" + customerId;
		}else if(StringUtil.isNotEmpty(origType) && !"222".equals(origType) ){
			return "redirect:/conference/showDetail?conferenceId=" + conferencePid;
		}else{
			//修改后跳转到专家管理页面
//			return "redirect:/person/findPersonList";
			//修改后跳转到专家详情页面
			return "redirect:/person/personDetails?pid="+person.getPid();
		}
	}
	
	/**
	 * 专家匹配需求页面
	 * @author dongli
	 * @date 2018年9月26日
	 * @param model
	 * @param person
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "mateDemandView")
	public String mateDemandView(Model model, Person person, HttpServletRequest request) {
		mateDemand(model, null, null, null, null, 1, person.getPid(), request);
		return "person/personOfDemandList";
	}
	
	/**
	 * 检索专家匹配需求
	 * @author dongli
	 * @date 2018年9月26日
	 * @param model
	 * @param researchField
	 * @param area
	 * @param searchKeyword
	 * @param domesticOrForeign
	 * @param pageNo
	 * @param personId
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")  //该注解表示忽略警告
	@RequestMapping(value = "mateDemand")
	public String mateDemand(Model model, String researchField, String area, String searchKeyword, Integer domesticOrForeign,
    		@RequestParam(defaultValue = "1") int pageNo, String personId, HttpServletRequest request) {
		
		String researchFieldWorth = StringUtil.isEmpty(researchField) ? null : getDicCheckboxWorth(StrUtil.stringByByte(researchField).toString(), Constant.DICTIONTRY_DEMANDFIELD);
    	String areaWorth = StringUtil.isEmpty(area) ? null : getAreaWorth(area, domesticOrForeign);
    	Person person = personService.getById(personId);
    	person.setResearchField(getDicCheckboxWorth(person.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
    	
        Pagination pagination = new SolrOperation<>().queryList(pageNo, DEFAULT_COUNT, 1, person.getPid(), researchFieldWorth, areaWorth, searchKeyword);
        //根据personId查询对接详情，然后筛选出已经对接过的demand
        ButtDetails buttDetails = new ButtDetails();
        //buttDetails.setButtPersonId(getUserId(request));
        buttDetails.setExpertNumber(personId);
        buttDetails.setFuture(1);
        buttDetails.setDemandNumberEmpty(false);
        List<ButtDetails> demandDetailList = detailsService.findButtDetails(buttDetails);
        
        List<String> demandDetailIdList = demandDetailList.stream().map(ButtDetails::getDemandNumber).collect(Collectors.toList());
        List<String> buttedDemandIdList =null;
        if(pagination!=null){
            List<LuceneDemand> list = pagination.getList();
    		buttedDemandIdList = list.stream().map(LuceneDemand::getDemandId).filter(StringUtil::isNotEmpty)
    				.filter(demandId -> demandDetailIdList.contains(demandId)).collect(Collectors.toList());
        }

		String[] researchFieldArr = StringUtil.isNotEmpty(researchField) ? researchFieldArr = researchField.split(",") : new String[0];
        if (StringUtil.isNotEmpty(area))
            areaModel(model, area, domesticOrForeign);
        
        addListToModel(model);
        model.addAttribute("researchFieldArr", researchFieldArr);
        model.addAttribute("pageInfo", pagination);
        model.addAttribute("person", person);
        model.addAttribute("buttedDemandIdList", buttedDemandIdList);
        model.addAttribute("domesticOrForeign", domesticOrForeign);

		return "person/personOfDemandList";
	}
	
	/**
	 * 下载专家匹配的需求
	 * @author dongli
	 * @date 2018年10月22日
	 * @param request
	 * @param response
	 * @param personId
	 */
	@RequestMapping("demandDownLoad")
	@ResponseBody
	public void demandDownLoad(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="personId",required=false) String personId){
		//1.
		List<List<String>> demandLists = Collections.synchronizedList(new ArrayList<List<String>>());
		//2.表头
		List<String> tagList = new ArrayList<>();
		tagList.add("需求ID");
		tagList.add("需求名称");
		tagList.add("需求类型");
		tagList.add("需求状态");
		tagList.add("需求内容");
		tagList.add("所属领域");
		tagList.add("需求联系人");
		tagList.add("手机");
		tagList.add("邮箱");
		//3.根据专家pid查询需求
		List<Demand> attrList = detailsService.queryDemandList(personId);
		for (Demand demand : attrList) {
			List<String> content = new ArrayList<>();
			content.add("D"+demand.getDemandNumber());
			content.add(demand.getDemandName());
			//需求类型
			demand.setDemandType(getDicCheckboxWorth(demand.getDemandType(), Constant.DICTIONTRY_DEMANDTYPE));
			content.add(demand.getDemandType()); 
			//需求状态
			demand.setDemandStatusWorth(getDicSingleWorth(demand.getDemandStatus(), Constant.DICTIONTRY_DEMANDSTATUS));
			content.add(demand.getDemandStatusWorth()); 
			content.add(demand.getDemandContent()); 
			//所属领域
			demand.setResearchField(getDicCheckboxWorth(demand.getResearchField(), Constant.DICTIONTRY_DEMANDFIELD));
			content.add(demand.getResearchField()); 
			//通过需求联系人查询专家
			Person person = personService.getById(demand.getDemandContactId());
			content.add(person.getName()); 
			//手机
			String tells = null;
			if (person.getTell() != null && person.getTell().length() >= 11) {
				tells = person.getTell().substring(0, 3) + "****" + person.getTell().substring(7, person.getTell().length());
			}else {
				tells = person.getTell();
			}
			content.add(tells);
			//邮箱
			String emails = null;
			if (person.getEmail() != null && person.getEmail().length() >= 5) {
				emails = "****" + person.getEmail().substring(4, person.getEmail().length());
			}else {
				emails = person.getEmail();
			}
			content.add(emails);
			
			//将多个list拼接成一个
			demandLists.add(content);
		}
		//4.下载excel至服务器
		File file=ExcelUtil.writeExcel(tagList, demandLists, "PersonButtDemandList.xls");
		//5.将服务器上文件下载至本地
		try {
			ExcelUtil.downLoad(request, file, response);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
	
	/**
	 * 查看需求详情
	 * @author dongli
	 * @date 2018年9月25日
	 * @param demandId
	 * @param model
	 * @return
	 */
	@RequestMapping("demandDetail")
    public String demandDetail(String demandId, String personId,Model model,String projectId, HttpServletRequest request) {
		Demand demand = demandService.getById(demandId);
        demand.setSourceWorth(getDicSingleWorth(demand.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
        demand.setDemandStatusWorth(getDicSingleWorth(demand.getDemandStatus(), Constant.DICTIONTRY_DEMANDSTATUS));
        demand.setDemandType(getDicCheckboxWorth(demand.getDemandType(), Constant.DICTIONTRY_DEMANDTYPE));
        demand.setResearchField(getDicCheckboxWorth(demand.getResearchField(), Constant.DICTIONTRY_DEMANDFIELD));
        demand.setAreaWorth(getAreaWorth(demand.getArea(), demand.getDomesticOrForeign()));
        model.addAttribute("demand", demand);
        model.addAttribute("collectPersonName", userService.getById(demand.getCollectPersonId()).getFullName());
        
        //查询联系人信息
        Person person = new Person();
        if(StringUtil.isNotEmpty(demand.getDemandContactId())) {
	        person = personService.findPersonByPid(demand.getDemandContactId());
	    	person.setSourceWorth(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
			person.setTypeWorth(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
			person.setResearchField(getDicCheckboxWorth(person.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
			if (StringUtil.isNotEmpty(person.getTalentLevel())) {
				person.setTalentLevel(getDicCheckboxWorth(person.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
			}
			person.setAreaWorth(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
        }
        model.addAttribute("person",person);
        model.addAttribute("personId",personId);
        if (StringUtil.isNotEmpty(projectId)) {
        	ButtDetails queryButt = new ButtDetails();
        	queryButt.setButtPersonId(getUserId(request));
        	queryButt.setFuture(1);
        	queryButt.setDemandNumber(demandId);
        	queryButt.setProjectNumber(projectId);
        	List<ButtDetails> buttDetailList = detailsService.findButtDetails(queryButt);
        	model.addAttribute("buttDetailList", buttDetailList);
        	model.addAttribute("project", projectService.getById(projectId));
        }
        
        return "person/demandDetail";
    }
	
	/**
	 * 匹配需求
	 * @author dongli
	 * @date 2018年8月30日
	 * @param demandId
	 * @param demand
	 * @param personId
	 * @param person
	 * @param request
	 * @return
	 */
	@RequestMapping("pipei")
    @ResponseBody
    public String pipei(String demandId, Demand demand, String personId, Person person, HttpServletRequest request) {
        demand.setPid(demandId);
        person.setPid(personId);
        detailsService.addFirstButtDetails(null, demand, null, null, person, getUserId(request));
        return "success";
    }
	
	/**
	 * 需求详情页面中当前需求匹配专家功能
	 * @author dongli
	 * @date 2018年9月27日
	 * @param demandId
	 * @param personId
	 * @param request
	 * @param buttDetails
	 * @return
	 */
	@RequestMapping("pipei1")
	@ResponseBody  //用于异步
    public String pipei1(String demandId, String personId, HttpServletRequest request,ButtDetails buttDetails) {
		//将需求pid和专家pid封装到详情中
        buttDetails.setDemandNumber(demandId);
        buttDetails.setExpertNumber(personId);
        //通过需求pid和专家pid查询详情
        List<ButtDetails> list = detailsService.findDetailsByPersonIdAndDemandId(buttDetails);
        //判断查询结果返回不同的值
        if (list != null && list.size()==1) {
        	//a.返回失败
        	return "fail";
		}else {
			Demand demand = demandService.getById(demandId);
	        Person person = personService.getById(personId);
	        //添加匹配数据
			detailsService.addFirstButtDetails(null, demand, null, null, person, getUserId(request));
			//b.返回成功
			return "success";
		}
    }
	
	/**
	 * 查看专家参会情况
	 * @author dongli
	 * @date 2018年8月24日
	 * @param pid
	 * @param model
	 * @param conference
	 * @param bindingResult
	 * @param pageNum
	 * @param conferenceNumberId
	 * @return
	 */
	@RequestMapping(value= "mateConference")
	public String mateConference(String pid,Person person, Model model,Conference conference, Integer pageNum,
			@RequestParam(value = "conferenceNumberId", required = false) String conferenceNumberId){
		
		addListToModel(model);
		String cityId = "";
		String province = "";

		if (StringUtil.isNotEmpty(conference.getArea()) && conference.getDomesticOrForeign()!=null) {
			areaModel(model, conference.getArea(), conference.getDomesticOrForeign());
		}
		// 分页
		if (null == pageNum) {
			pageNum = 1;
		}
		String conferenNum = "";
		// 重新复制客户id
		if (StringUtil.isNotEmpty(conferenceNumberId)) {
			conferenNum = String.valueOf(conferenceNumberId.trim());
			// 去除字母
			conferenNum = conferenNum.replaceAll("[a-zA-Z]", "");
		}
		if (StringUtil.isNotEmpty(conferenNum)) {
			conference.setConferenceNumber(Integer.parseInt(conferenNum));
		}
		if (StringUtil.isNotEmpty(conference.getConferenceName())) {
			conference.setConferenceName(conference.getConferenceName().trim());
		}
		String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(conference.getResearchField())) {
			researchFieldArr = conference.getResearchField().split(",");
			conference.setResearchFieldNumber(researchFieldArr.length);
			conference.setResearchFieldInteger(StrUtil.stringByByte(conference.getResearchField()));
		}
		model.addAttribute("researchFieldArr", researchFieldArr);
		
		//通过专家id，查询中间表中会议的数据
		List<Conference> confList = null;
		List<ConfOfAttr> findAttrByPerson = conOfAttrService.findAttrByPersonId(pid);
		//判断通过专家id是否在中间表中查到了数据
		if(findAttrByPerson!=null && findAttrByPerson.size()>0){
			//得到会议id数组
			String [] conferenceIds = new String[findAttrByPerson.size()];
			for (int i = 0; i < findAttrByPerson.size(); i++) {
				//将中间表中获得的会议id循环加入到会议中
				conferenceIds[i] = findAttrByPerson.get(i).getConferenceId();
			}
			Conference conf=new Conference();
			//会议数组
			conf.setInPersonIds(conferenceIds);
			//分页插件
			PageHelper.startPage(pageNum, BaseController.DEFAULT_COUNT);
			//通过会议id数组查询会议
		    confList = conferenceService.queryInConferenceIds(conf);
		    for (int i = 0; i < confList.size(); i++) {
				String areaStr = "";
				String reachName = "";
				// 得到所属领域二进制
				String rearch = confList.get(i).getResearchField();
				// 得到areaId
				String areaIdStr = String.valueOf(confList.get(i).getArea());
				if (areaIdStr != null && !"".equals(areaIdStr) && !"null".equals(areaIdStr)) {
					if (areaIdStr.length() == 4) {
						// 说明是国外的
						Dictiontry dicArea = new Dictiontry();
						dicArea.setPid(Integer.parseInt(areaIdStr));
						dicArea.setGroupName(Constant.DICTIONTRY_COUNTRY);
						// 国外的名字
						areaStr=getAreaWorth(areaIdStr, 1);
					}
					if (areaIdStr.length() < 10 && areaIdStr.length() > 5) {
						// 说明是区的id
						// 截取得到省和市的id
						Dictiontry dicArea = new Dictiontry();
						dicArea.setNames(areaIdStr);
						dicArea.setGroupName(Constant.DICTIONTRY_AREA);
						areaStr=getAreaWorth(areaIdStr, 0);
					}
					if (areaIdStr.length() < 6 && areaIdStr.length() > 2 && areaIdStr.length() != 4) {
						// 说明是市的id
						Dictiontry dicArea = new Dictiontry();
						cityId = areaIdStr.substring(0, 5);
						dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
						dicArea.setNames(cityId);
						areaStr=getAreaWorth(areaIdStr, 0);
					}
					if (areaIdStr.length() < 3 && areaIdStr.length() > 0) {
						// 说明是省的id
						Dictiontry dicArea = new Dictiontry();
						province = areaIdStr.substring(0, 2);
						dicArea.setNames(province);
						dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
						// 省的名字
						areaStr=getAreaWorth(areaIdStr, 0);
					}
				}
				// 给地区附上名字
				confList.get(i).setAreaNameStr(areaStr);
				//取最右地区
				if(areaStr.contains("-")){
					String [] areaArray=areaStr.split("-");
					String lastArea=areaArray[areaArray.length-1];
					confList.get(i).setAreaNameArray(lastArea);
				}else{
					confList.get(i).setAreaNameArray(areaStr);
				}
				// 二进制转化为字符串
				reachName=getDicCheckboxWorth(rearch, Constant.DICTIONTRY_PROJECTFIELD);
				confList.get(i).setResearchFieldNameStr(reachName);
			}
		}
	
		// 将list放进PageInfo
		PageInfo<Conference> pageInfo = new PageInfo<Conference>(confList);
		model.addAttribute("pageInfo", pageInfo);
		//通过pid查询专家
		Person tempPerson =personService.findPersonByPid(pid);
		
		model.addAttribute("personInfo",tempPerson);
		return "person/personOfConferenceList";
	}
	
	/**
	 * 下载参会情况
	 * @author dongli
	 * @date 2018年10月22日
	 * @param request
	 * @param response
	 * @param personId
	 */
	@RequestMapping("conferenceDownLoad")
	@ResponseBody
	public void conferenceDownLoad(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="personId",required=false) String personId){
		//1.
		List<List<String>> contentLists = Collections.synchronizedList(new ArrayList<List<String>>());
		//2.表头
		List<String> tagList = new ArrayList<>();
		tagList.add("活动ID");
		tagList.add("活动名称");
		tagList.add("开始时间");
		tagList.add("结束时间");
		tagList.add("所属领域");
		tagList.add("所在地区");
		tagList.add("执行团队");
		//3.根据专家pid查询中间表中关联的会议信息，遍历
		List<Conference> attrList = conOfAttrService.queryConferenceList(personId);
		for (Conference conference : attrList) {
			List<String> content = new ArrayList<>();
			content.add("A"+conference.getConferenceNumber());
			content.add(conference.getConferenceName());
			content.add(conference.getConferenceDateTime());
			content.add(conference.getConferenceBeginTime());
			
			//所属领域
			String reachName = getDicCheckboxWorth(conference.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD);
			conference.setResearchFieldNameStr(reachName);
			content.add(conference.getResearchFieldNameStr());
			
			//所在地区
			String areaStr = "";
			String areaIdStr = String.valueOf(conference.getArea());
			if (areaIdStr != null && !"".equals(areaIdStr) && !"null".equals(areaIdStr)) {
				if (areaIdStr.length() == 4) {
					// 说明是国外的
					Dictiontry dicArea = new Dictiontry();
					dicArea.setPid(Integer.parseInt(areaIdStr));
					dicArea.setGroupName(Constant.DICTIONTRY_COUNTRY);
					// 国外的名字
					areaStr=getAreaWorth(areaIdStr, 1);
				}
				if (areaIdStr.length() < 10 && areaIdStr.length() > 5) {
					// 说明是区的id
					// 截取得到省和市的id
					Dictiontry dicArea = new Dictiontry();
					dicArea.setNames(areaIdStr);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA);
					areaStr=getAreaWorth(areaIdStr, 0);
				}
				if (areaIdStr.length() < 6 && areaIdStr.length() > 2 && areaIdStr.length() != 4) {
					// 说明是市的id
					Dictiontry dicArea = new Dictiontry();
					String cityId = areaIdStr.substring(0, 5);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
					dicArea.setNames(cityId);
					areaStr=getAreaWorth(areaIdStr, 0);
				}
				if (areaIdStr.length() < 3 && areaIdStr.length() > 0) {
					// 说明是省的id
					Dictiontry dicArea = new Dictiontry();
					String province = areaIdStr.substring(0, 2);
					dicArea.setNames(province);
					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
					// 省的名字
					areaStr=getAreaWorth(areaIdStr, 0);
				}
			}
			// 给地区附上名字
			conference.setAreaNameStr(areaStr);
			content.add(conference.getAreaNameStr());
			
			content.add(conference.getTearm());
			//将多个list拼接成一个
			contentLists.add(content);
		}
		//4.下载excel至服务器
		File file=ExcelUtil.writeExcel(tagList, contentLists, "PersonButtConferenceList.xls");
		//5.将服务器上文件下载至本地
		try {
			ExcelUtil.downLoad(request, file, response);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}
	
	/**
	 * 查看专家匹配需求详情
	 * @author dongli
	 * @date 2018年8月22日
	 * @param model
	 * @return
	 */
	@RequestMapping(value= "findButtDetailsList",produces="application/json;charset=UTF-8")
	public String findButtDetailsList(String pid,@RequestParam(defaultValue = "1") int pageNo,ButtDetails buttDetails,Model model,HttpServletRequest request){
		// 分页
		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);
		
		//设置对接状态
		if(buttDetails.getButtStatus()!=null && buttDetails.getButtStatus()==0){
			buttDetails.setButtStatus(1);
		}
		// 将专家的pid封装到对接详情中
		buttDetails.setExpertNumber(pid);
		//buttDetails.setButtPersonId(getUserId(request)); 要求可以查询到所有用户匹配过的信息
		buttDetails.setFuture(1);
		buttDetails.setDemandNumberEmpty(false);
		
		List<ButtDetails> list1 = detailsService.findButtDetails(buttDetails);
		//将list放进PageInfo
		PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(list1);
		//通过pid查询专家
		Person person = personService.findPersonByPid(pid);
		//专家的所属领域
    	person.setResearchField(getDicCheckboxWorth(person.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));

		//从缓存中获取对接状态
		List<Dictiontry> buttStatus=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("buttStatus", buttStatus); //集合
		model.addAttribute("person", person);
		
		//查询已经更新过的对接详情
        ButtDetails buttDetails1 = new ButtDetails();
        buttDetails1.setButtPersonId(getUserId(request)); //目的是为了不撤销其他用户的
        buttDetails1.setExpertNumber(person.getPid());
        buttDetails1.setFuture(0); //过时
        buttDetails1.setDemandNumberEmpty(false);
        List<ButtDetails> updatedDemandDetailList = detailsService.findButtDetails(buttDetails1);
		//已经更新过对接详情的所有需求ID
        List<String> updatedDemandIdList = updatedDemandDetailList.stream().map(ButtDetails::getDemandNumber).distinct().collect(Collectors.toList());
        model.addAttribute("updatedDemandIdList", updatedDemandIdList);

		return "person/person_buttDemandDetails";
	}
	
	/**
	 * 撤销匹配
	 * @author dongli
	 * @date 2018年10月26日
	 * @param person
	 * @param request
	 * @param model
	 * @param pageNo
	 * @param buttId
	 * @param buttDetails
	 * @return
	 */
	@RequestMapping("/deleteDemandButt")
    public String deleteDemandButt(Person person,ButtDetails buttDetails, HttpServletRequest request, Model model,
    		@RequestParam(defaultValue = "1") int pageNo, String buttId) {
    	detailsService.delete(buttId);
    	return findButtDetailsList(person.getPid(),pageNo,buttDetails,model,request);
    }
	
	/**
	 * 下载详情附件
	 * @author dongli
	 * @date 2018年8月29日
	 * @param request
	 * @param response
	 * @param fileName
	 * @return
	 */
	@RequestMapping("download")
	public String downloadFile(HttpServletRequest request, HttpServletResponse response,String fileName) {
	 
	    if (fileName != null) {
	        //设置文件路径
	        String realPath = Constant.DEF_BUT_DETAILS_PATH;
	        File file = new File(realPath , fileName);
	        if (file.exists()) {
	            response.setContentType("application/force-download");// 设置强制下载不打开
	            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
	            byte[] buffer = new byte[1024];
	            FileInputStream fis = null;
	            BufferedInputStream bis = null;
	            try {
	                fis = new FileInputStream(file);
	                bis = new BufferedInputStream(fis);
	                OutputStream os = response.getOutputStream();
	                int i = bis.read(buffer);
	                while (i != -1) {
	                    os.write(buffer, 0, i);
	                    i = bis.read(buffer);
	                }
	                //System.out.println("success");
	            } catch (Exception e) {
	                e.printStackTrace();
	            } finally {
	                if (bis != null) {
	                    try {
	                        bis.close();
	                    } catch (IOException e) {
	                        e.printStackTrace();
	                    }
	                }
	                if (fis != null) {
	                    try {
	                        fis.close();
	                    } catch (IOException e) {
	                        e.printStackTrace();
	                    }
	                }
	            }
	        }
	    }
	    return null;
	}
	
	/**
	 * 查看专家匹配的历史详情
	 * @author dongli
	 * @date 2018年8月29日
	 * @param pageNo
	 * @param buttdetails
	 * @param request
	 * @return
	 */
	@RequestMapping("findHistoryButtDetails")
	public  String findHistoryButtDetails(Integer pageNo,String pid ,HttpServletRequest request,Model model){
		try{
			//从缓存中获取对接状态
			List<Dictiontry> buttStatus=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
			request.setAttribute("buttStatus", buttStatus);
			//通过对接详情pid查询对接详情
			ButtDetails buttd= detailsService.findDetailsByPid(pid);
			//分页
			if(null==pageNo){
				pageNo=1;
			}
			 PageHelper.startPage(pageNo, DEFAULT_COUNT);
			 //将future设置为0，表示过期数据
			 buttd.setFuture(null);
			 //通过外键查询对接详情
			 List <ButtDetails> listbutt = detailsService.findHistoryButtDetails(buttd);
			 Person person = personService.findPersonByPid(buttd.getExpertNumber());
			 
			 PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(listbutt);
			 request.setAttribute("pageInfo", pageInfo);
			 request.setAttribute("person", person);
			 request.setAttribute("buttd", buttd);
			 
		}catch(Exception e){
			logger.error( e.getMessage());
		}
		return "person/person_historyDetails";
	}
	
	/**
	 * 从专家详情页里查看历史详情
	 * @author dongli
	 * @date 2018年10月19日
	 * @param pageNo
	 * @param pid
	 * @param request
	 * @return
	 */
	@RequestMapping("findHistoryButtDetails1")
	public  String findHistoryButtDetails1(Integer pageNo,String pid ,HttpServletRequest request){
		try{
			//从缓存中获取对接状态
			List<Dictiontry> buttStatus=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
			request.setAttribute("buttStatus", buttStatus);
			//通过对接详情pid查询对接详情
			ButtDetails buttd= detailsService.findDetailsByPid(pid);
			//分页
			if(null==pageNo){
				pageNo=1;
			}
			 PageHelper.startPage(pageNo, DEFAULT_COUNT);
			 //将future设置为0，表示过期数据
			 buttd.setFuture(null);
			 //通过外键查询对接详情
			 List <ButtDetails> listbutt = detailsService.findHistoryButtDetails(buttd);
			 Person person = personService.findPersonByPid(buttd.getExpertNumber());
			 
			 PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(listbutt);
			 request.setAttribute("pageInfo", pageInfo);
			 request.setAttribute("person", person);
			 request.setAttribute("buttd", buttd);
			 
		}catch(Exception e){
			logger.error( e.getMessage());
		}
		return "person/person_historyDetails1";
	}

	/**
	 * 进入添加对接详情页面
	 * @author dongli
	 * @date 2018年8月31日
	 * @param pid
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addDetailsView",produces="application/json;charset=UTF-8")
	public String addDetailsView(String pid,Model model){
		//从缓存中获取对接状态
		List<Dictiontry> buttStatus=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		//新建对接详情
		ButtDetails buttDeteils = new ButtDetails();
		model.addAttribute("buttDeteils", buttDeteils);
		model.addAttribute("pid", pid);
		model.addAttribute("buttStatus", buttStatus);
		//通过pid查询对接详情
		ButtDetails de =detailsService.findDetailsByPid(pid);
		model.addAttribute("details",de.getButtDetails());
		model.addAttribute("de", de);
		//获取需求和专家
		if (de != null) {
			if(de.getDemandNumber()!=null&&!"".equals(de.getDemandNumber())){
				Demand demand =demandService.getById(de.getDemandNumber());
				model.addAttribute("demand", demand);
			}
			if(de.getExpertNumber()!=null&&!"".equals(de.getExpertNumber())){
				Person person =personService.getById(de.getExpertNumber());
				model.addAttribute("person", person);
			}
		}
		
		return "person/person_addDetailsView";
	}
	
	/**
	 * 从专家详情页面进入添加对接详情页面
	 * @author dongli
	 * @date 2018年10月19日
	 * @param pid
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "addDetailsView1",produces="application/json;charset=UTF-8")
	public String addDetailsView1(String pid,Model model){
		//从缓存中获取对接状态
		List<Dictiontry> buttStatus=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
		//新建对接详情
		ButtDetails buttDeteils = new ButtDetails();
		model.addAttribute("buttDeteils", buttDeteils);
		model.addAttribute("pid", pid);
		model.addAttribute("buttStatus", buttStatus);
		//通过pid查询对接详情
		ButtDetails de =detailsService.findDetailsByPid(pid);
		model.addAttribute("details",de.getButtDetails());
		model.addAttribute("de", de);
		//获取需求和专家
		if (de != null) {
			if(de.getDemandNumber()!=null&&!"".equals(de.getDemandNumber())){
				Demand demand =demandService.getById(de.getDemandNumber());
				model.addAttribute("demand", demand);
			}
			if(de.getExpertNumber()!=null&&!"".equals(de.getExpertNumber())){
				Person person =personService.getById(de.getExpertNumber());
				model.addAttribute("person", person);
			}
		}
		
		return "person/person_addDetailsView1";
	}
	
	/**
	 * 专家匹配需求详情页里添加对接详情
	 * @author dongli
	 * @date 2018年8月31日
	 * @param buttDetails
	 * @param bindingResult
	 * @param pid
	 * @param buttDetailsFiles
	 * @param model
	 * @param request
	 * @return
	 */
	@Log("修改对接详情")
	@RequestMapping(value = "addDetails" , method = RequestMethod.POST)
	public String addDetails(@RefPid @Valid ButtDetails buttDetails, BindingResult bindingResult,String pid,
			MultipartFile buttDetailsFiles, Model model, HttpServletRequest request){
		//创建一个空的对象
		ButtDetails oldButt = null;
		try{
			//通过pid查询对接详情
			oldButt = detailsService.findDetailsByPid(pid);
			//添加字段信息
			buttDetails.setFuture(1);
			buttDetails.setAddDateTime(StrUtil.getCurrentDateTime_two());
			buttDetails.setButtPersonId(this.getUserId(request)); //对接人一定要加上
			buttDetails.setButtName(this.getUserInfoBySession(request).getFullName());
			//文件上传
			if (null!=buttDetailsFiles && !buttDetailsFiles.isEmpty()) {
				// 文件名字
				String fileName = buttDetailsFiles.getOriginalFilename();
				String oldFileName = FileUtils.generateFileName("buttdetails", fileName);
				
				buttDetails.setButtaNnex(oldFileName);
				try {
					FileUtils.uploadFile(buttDetailsFiles.getBytes(), Constant.DEF_BUT_DETAILS_PATH, oldFileName);
				} catch (Exception e) {
					logger.error("上传文件失败：" + e.getMessage());
				}
			}else {
				//当附件为空的时候不改变原来附件的内容
				String fileName = FileUtils.transferTo(Constant.DEF_BUT_DETAILS_PATH, buttDetailsFiles, "buttDetails");
				ButtDetails butt = detailsService.findDetailsByPid(pid);
				fileName = StringUtil.isEmpty(fileName) ? butt.getButtaNnex() : fileName ;
				buttDetails.setButtaNnex(fileName);
			}
			//添加
			detailsService.addButtDetails(oldButt,buttDetails);
		}catch(Exception e){
			logger.error( e.getMessage());
		}
		
		//1.重定向到专家匹配需求详情页面
		return "redirect:/person/findButtDetailsList?pid="+oldButt.getExpertNumber();
		//2.重定向到专家详情页面  
//		return "redirect:/person/personDetails?pid="+oldButt.getExpertNumber();
	}
	
	/**
	 * 专家详情页里添加对接详情
	 * @author dongli
	 * @date 2018年10月19日
	 * @param buttDetails
	 * @param bindingResult
	 * @param pid
	 * @param buttDetailsFiles
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "addDetails1" , method = RequestMethod.POST)
	public String addDetails1(@Valid ButtDetails buttDetails, BindingResult bindingResult,String pid,
			MultipartFile buttDetailsFiles, Model model, HttpServletRequest request){
		//创建一个空的对象
		ButtDetails oldButt = null;
		try{
			//通过pid查询对接详情
			oldButt = detailsService.findDetailsByPid(pid);
			//添加字段信息
			buttDetails.setFuture(1);
			buttDetails.setAddDateTime(StrUtil.getCurrentDateTime_two());
			buttDetails.setButtPersonId(this.getUserId(request)); //对接人一定要加上
			buttDetails.setButtName(this.getUserInfoBySession(request).getFullName());
			//文件上传
			if (null!=buttDetailsFiles && !buttDetailsFiles.isEmpty()) {
				// 文件名字
				String fileName = buttDetailsFiles.getOriginalFilename();
				String oldFileName = FileUtils.generateFileName("buttdetails", fileName);
				
				buttDetails.setButtaNnex(oldFileName);
				try {
					FileUtils.uploadFile(buttDetailsFiles.getBytes(), Constant.DEF_BUT_DETAILS_PATH, oldFileName);
				} catch (Exception e) {
					logger.error("上传文件失败：" + e.getMessage());
				}
			}else {
				//当附件为空的时候不改变原来附件的内容
				String fileName = FileUtils.transferTo(Constant.DEF_BUT_DETAILS_PATH, buttDetailsFiles, "buttDetails");
				ButtDetails butt = detailsService.findDetailsByPid(pid);
				fileName = StringUtil.isEmpty(fileName) ? butt.getButtaNnex() : fileName ;
				buttDetails.setButtaNnex(fileName);
			}
			//添加
			detailsService.addButtDetails(oldButt,buttDetails);
		}catch(Exception e){
			logger.error( e.getMessage());
		}
		
		//重定向到专家详情页面  
		return "redirect:/person/personDetails?pid="+oldButt.getExpertNumber();
	}
	
	/**
	 * 查看专家详情
	 * @author dongli
	 * @date 2018年8月23日
	 * @param pid
	 * @param model
	 * @return
	 */
	@RequestMapping(value= "personDetails",produces="application/json;charset=UTF-8")
	public String personDetails(@RequestParam("pid") String pid,Model model,@RequestParam(defaultValue = "1") int pageNo,HttpServletRequest request, ButtDetails buttDetails,
			Person person,Conference conference,String conferenceNumberId, String demId,Integer lookExpert, String lookPwd){
		
		//通过pid查询专家表
		Person per = personService.findPersonByPid(pid);
		//通过pid查询用户
		User user = userService.findUserById(per.getCollectPersonId());
		
		per.setSourceWorth(getDicSingleWorth(per.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
		per.setTypeWorth(getDicSingleWorth(per.getType(), Constant.DICTIONTRY_PERSONTYPE));
		per.setResearchField(getDicCheckboxWorth(per.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
		if (per.getTalentLevel() != null) {
			per.setTalentLevel(getDicCheckboxWorth(per.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
		}
		per.setAreaWorth(getAreaWorth(per.getArea(), per.getDomesticOrForeign()));
		
		//1.专家已匹配需求详情
		buttDetails.setExpertNumber(pid);;
		//buttDetails.setButtPersonId(getUserId(request)); //不同的对接人添加的数据所有人都可以看到
		buttDetails.setFuture(1);
		buttDetails.setDemandNumberEmpty(false);
		List<ButtDetails> list = detailsService.findButtDetailsTop10(buttDetails);
		//将list放进PageInfo1，避免和参会情况中的pageInfo发生冲突
		PageInfo<ButtDetails> pageInfo1 = new PageInfo<ButtDetails>(list);
		
		//2.专家参会情况
		String cityId = "";
		String province = "";
		//通过专家id，查询中间表中会议的数据
		List<Conference> confList = null;
		List<ConfOfAttr> findAttrByPerson = conOfAttrService.findAttrByPersonId(pid);
		//判断通过专家id是否在中间表中查到了数据
		if (findAttrByPerson != null && findAttrByPerson.size() > 0) {
			//得到会议id数组
			String [] conferenceIds = new String[findAttrByPerson.size()];
			for (int i = 0; i < findAttrByPerson.size(); i++) {
				//将中间表中获得的会议id循环加入到会议中
				conferenceIds[i] = findAttrByPerson.get(i).getConferenceId();
			}
			Conference conf=new Conference();
			//会议数组
			conf.setInPersonIds(conferenceIds);
			//通过会议id数组查询会议
			confList = conferenceService.queryInConferenceIdsTop10(conf);
			for (int i = 0; i < confList.size(); i++) {
				String areaStr = "";
				String reachName = "";
				// 得到所属领域二进制
				String rearch = confList.get(i).getResearchField();
				// 得到areaId
				String areaIdStr = String.valueOf(confList.get(i).getArea());
				if (areaIdStr != null && !"".equals(areaIdStr) && !"null".equals(areaIdStr)) {
					if (areaIdStr.length() == 4) {
						// 说明是国外的
						Dictiontry dicArea = new Dictiontry();
						dicArea.setPid(Integer.parseInt(areaIdStr));
						dicArea.setGroupName(Constant.DICTIONTRY_COUNTRY);
						// 国外的名字
						areaStr=getAreaWorth(areaIdStr, 1);
					}
					if (areaIdStr.length() < 10 && areaIdStr.length() > 5) {
						// 说明是区的id
						// 截取得到省和市的id
						Dictiontry dicArea = new Dictiontry();
						dicArea.setNames(areaIdStr);
						dicArea.setGroupName(Constant.DICTIONTRY_AREA);
						areaStr=getAreaWorth(areaIdStr, 0);
					}
					if (areaIdStr.length() < 6 && areaIdStr.length() > 2 && areaIdStr.length() != 4) {
						// 说明是市的id
						Dictiontry dicArea = new Dictiontry();
						cityId = areaIdStr.substring(0, 5);
						dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
						dicArea.setNames(cityId);
						areaStr=getAreaWorth(areaIdStr, 0);
					}
					if (areaIdStr.length() < 3 && areaIdStr.length() > 0) {
						// 说明是省的id
						Dictiontry dicArea = new Dictiontry();
						province = areaIdStr.substring(0, 2);
						dicArea.setNames(province);
						dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
						// 省的名字
						areaStr=getAreaWorth(areaIdStr, 0);
					}
				}
				// 给地区附上名字
				confList.get(i).setAreaNameStr(areaStr);
				//取最右地区
				if(areaStr.contains("-")){
					String [] areaArray=areaStr.split("-");
					String lastArea=areaArray[areaArray.length-1];
					confList.get(i).setAreaNameArray(lastArea);
				}else{
					confList.get(i).setAreaNameArray(areaStr);
				}
				// 二进制转化为字符串
				reachName=getDicCheckboxWorth(rearch, Constant.DICTIONTRY_PROJECTFIELD);
				confList.get(i).setResearchFieldNameStr(reachName);
			}
		}
		// 将list放进PageInfo
		PageInfo<Conference> pageInfo2 = new PageInfo<Conference>(confList);
		
		//3.专家未匹配需求详情
        Pagination pagination = new SolrOperation<>().queryList(pageNo, DEFAULT_COUNT, 1, per.getPid(), null, null, null);
        //根据projectid查询对接详情，然后筛选出已经对接过的demand
        ButtDetails buttDetails1 = new ButtDetails();
        //buttDetails1.setButtPersonId(getUserId(request));
        buttDetails1.setExpertNumber(pid);
        buttDetails1.setFuture(1);
        buttDetails1.setDemandNumberEmpty(false);
        List<ButtDetails> demandDetailList = detailsService.findButtDetails(buttDetails1);
        List<String> demandDetailIdList = demandDetailList.stream().map(ButtDetails::getDemandNumber).collect(Collectors.toList());
        List<String> buttedDemandIdList =null;
        if(pagination!=null){
        	 List<LuceneDemand> list11 = pagination.getList();
     		 buttedDemandIdList = list11.stream().map(LuceneDemand::getDemandId).filter(StringUtil::isNotEmpty)
     				.filter(demandId -> demandDetailIdList.contains(demandId)).collect(Collectors.toList());
        }
       
        
		//在专家详情页面直接匹配
		if (StringUtil.isNotEmpty(demId)) {
        	ButtDetails queryButt = new ButtDetails();
        	queryButt.setButtPersonId(getUserId(request));
        	queryButt.setFuture(1);
        	queryButt.setDemandNumber(demId);
        	queryButt.setExpertNumber(pid);
        	List<ButtDetails> buttDetailList = detailsService.findButtDetails(queryButt);
        	model.addAttribute("buttDetailList", buttDetailList);
        	model.addAttribute("demand", demandService.getById(demId));
        }
		
		/**
		 * 4.专家关联项目
		 */
		//a.联系人
		Project project = new Project();
		project.setProjectContactId(pid);
		List<Project> list3 = projectService.findProjectByProjectContactId(project);
		list3.forEach(project1 -> project1.setProjectType(getDicCheckboxWorth(project1.getProjectType(), Constant.DICTIONTRY_PROJECTTYPE)));
		list3.forEach(project1 -> project1.setProjectStatusWorth(getDicSingleWorth(project1.getProjectStatus(), Constant.DICTIONTRY_PROJECTSTATUS)));
        PageInfo<Project> pageInfo4 = new PageInfo<Project>(list3);
        //b.持有人
        ProjectOfPerson projectOfPerson = new ProjectOfPerson();
        projectOfPerson.setPersonId(pid);
        List<Project> list4 = projectOfPersonService.findProjectByProjectHolder(projectOfPerson);
        list4.forEach(project2 -> project2.setProjectType(getDicCheckboxWorth(project2.getProjectType(), Constant.DICTIONTRY_PROJECTTYPE)));
		list4.forEach(project2 -> project2.setProjectStatusWorth(getDicSingleWorth(project2.getProjectStatus(), Constant.DICTIONTRY_PROJECTSTATUS)));
		PageInfo<Project> pageInfo5 = new PageInfo<Project>(list4);
		
		//5.专家关联需求
		Demand demand = new Demand();
		demand.setDemandContactId(pid); //将专家pid放进需求联系人中
		List<Demand> list2 = demandService.findDemandByPersonId(demand);
		list2.forEach(demand1 -> demand1.setDemandType(getDicCheckboxWorth(demand1.getDemandType(), Constant.DICTIONTRY_DEMANDTYPE)));
        list2.forEach(demand1 -> demand1.setDemandStatusWorth(getDicSingleWorth(demand1.getDemandStatus(), Constant.DICTIONTRY_DEMANDSTATUS)));
		PageInfo<Demand> pageInfo3 = new PageInfo<Demand>(list2);
		
		//用户有20次免密查看专家的联系方式，20-40次需要密码查看，超过40次不能查看
		//lookExpert为1表示要查看联系方式
        if (lookExpert != null && lookExpert.equals(1)) 
        	checkLookExpert(pid, lookPwd, request);
		
		addListToModel(model);
        model.addAttribute("buttedDemandIdList", buttedDemandIdList);
        model.addAttribute("pageInfo", pagination);
		model.addAttribute("pageInfo1", pageInfo1);
		model.addAttribute("pageInfo2", pageInfo2);
		model.addAttribute("pageInfo3", pageInfo3);
		model.addAttribute("pageInfo4", pageInfo4);
		model.addAttribute("pageInfo5", pageInfo5);
		model.addAttribute("person",per);
		model.addAttribute("user",user);
		
		return "person/personDetails";
	}
	
	/**
	 * 下载专家附件
	 * @author dongli
	 * @date 2018年9月10日
	 * @param request
	 * @param response
	 * @param fileName
	 * @return
	 */
	@RequestMapping("downloadPerson")
	public String downloadPersonFile(HttpServletRequest request, HttpServletResponse response,String fileName) {
	 
	    if (fileName != null) {
	        //设置文件路径
	        String realPath = Constant.DEF_PERSON_PATH;
	        File file = new File(realPath , fileName);
	        if (file.exists()) {
	            response.setContentType("application/force-download");// 设置强制下载不打开
	            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
	            byte[] buffer = new byte[1024];
	            FileInputStream fis = null;
	            BufferedInputStream bis = null;
	            try {
	                fis = new FileInputStream(file);
	                bis = new BufferedInputStream(fis);
	                OutputStream os = response.getOutputStream();
	                int i = bis.read(buffer);
	                while (i != -1) {
	                    os.write(buffer, 0, i);
	                    i = bis.read(buffer);
	                }
	                System.out.println("success");
	            } catch (Exception e) {
	                e.printStackTrace();
	            } finally {
	                if (bis != null) {
	                    try {
	                        bis.close();
	                    } catch (IOException e) {
	                        e.printStackTrace();
	                    }
	                }
	                if (fis != null) {
	                    try {
	                        fis.close();
	                    } catch (IOException e) {
	                        e.printStackTrace();
	                    }
	                }
	            }
	        }
	    }
	    return null;
	}
	
	/**
	 * 提取的公共方法
	 */
	public void getData(Map<String, Object> map, Person person1){
		//设置表头ID
		String expertNumbers = "E" + person1.getExpertNumber();
		map.put("expertNumber", expertNumbers);
		//创建list集合
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		//创建Map集合用来存放专家的字段信息
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("name", person1.getName());
		String sexs = (person1.getSex() == null ? "" : person1.getSex() == 0 ? "男" : "女");
		map2.put("sex", sexs);
		map2.put("birth", person1.getBirth());
		map2.put("birthPlace", person1.getBirthPlace());
		//专家类型
		person1.setTypeWorth(getDicSingleWorth(person1.getType(), Constant.DICTIONTRY_PERSONTYPE));
		map2.put("type", person1.getTypeWorth());
		//所属领域
		person1.setResearchField(getDicCheckboxWorth(person1.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
		map2.put("researchField", person1.getResearchField());
		map2.put("schoolAndMajor", person1.getSchoolAndMajor());
		map2.put("maxEducation", person1.getMaxEducation());
		map2.put("unit", person1.getUnit());
		map2.put("title", person1.getTitle());
		map2.put("professionaField", person1.getProfessionaField());
		//人才级别
		if (person1.getTalentLevel() != null) {
			person1.setTalentLevel(getDicCheckboxWorth(person1.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
		}
		map2.put("talentLevel", person1.getTalentLevel());
		map2.put("education", person1.getEducation());
		map2.put("workExp", person1.getWorkExp());
		map2.put("technica", person1.getTechnica());
		map2.put("personInfo", person1.getPersonInfo());
		String tells = null;
		if (person1.getTell() != null && person1.getTell().length() >= 11) {
			tells = person1.getTell().substring(0, 3) + "****" + person1.getTell().substring(7, person1.getTell().length());
		}else {
			tells = person1.getTell();
		}
		map2.put("tell", tells);
		String emails = null;
		if (person1.getEmail() != null && person1.getEmail().length() >= 5) {
			emails = "****" + person1.getEmail().substring(4, person1.getEmail().length());
		}else {
			emails = person1.getEmail();
		}
		map2.put("email", emails);
		//专家任职状态
		if (person1.getRetireStatus() != null) {
			person1.setRetireStatusWorth(getDicSingleWorth(person1.getRetireStatus(), Constant.DICTIONTRY_PERSONRETIRE));
		}
		map2.put("retireStatus", person1.getRetireStatusWorth());
		//将专家信息存放在list中
		list.add(map2);
		//将list放进map中
		map.put("list", list);
	}
	
	/**
	 * 下载单个专家信息生成word文档
	 * @author dongli
	 * @date 2018年11月5日
	 * @return
	 */
	@RequestMapping("downLoadPer")
//	@ResponseBody  //防止解析错误
	public String downLoadPer(@RequestParam("pid") String pid,Model model,HttpServletRequest request,HttpServletResponse response, Integer pageNo,String expertNumberId){
		//通过用户id查询专家的下载量
		UserDownPerson userDownPerson1 = new UserDownPerson();
		userDownPerson1.setUserId(getUserId(request));
		userDownPerson1.setDownTime(StrUtil.getCurrentDateTime("yyyy-MM-dd"));
		//查询用户当天下载的条数
		Integer integer = userDownPersonService.findCountByUser(userDownPerson1);
		//通过用户id查询下载量（张三一天有200条下载量）
		Integer userDowns = userService.getById(getUserId(request)).getDownLoads();
		//如果库存量大于等于下载量
		if (userDowns <= integer) {
			model.addAttribute("max", "每天最多只能下载200条！");
			return findPersonList(pageNo, new Person(), model, expertNumberId, request);
		}else {
			//将下载的数据存入数据库
			UserDownPerson userDownPerson = new UserDownPerson();
			userDownPerson.setPid(StrUtil.getUUID32());
			userDownPerson.setUserId(getUserId(request));
			userDownPerson.setPersonId(pid);  //应该是在循环中获取专家id
			userDownPerson.setDownTime(StrUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
			userDownPersonService.add(userDownPerson);
			
			//创建配置
			Configuration configuration = new Configuration();
			//设置编码格式
			configuration.setDefaultEncoding("UTF-8");
			//通过专家pid查询专家
			Person person1 = personService.findPersonByPid(pid);
			//创建Map集合
			Map<String, Object> map = new HashMap<String,Object>();
			//调用本类方法
			getData(map,person1);
			
			//设置模板文件所在路径
			configuration.setClassForTemplateLoading(this.getClass(), "/templates");
			Template t = null;
			try {
				t = configuration.getTemplate("personWord1.ftl"); //获取模板文件
			} catch (IOException e) {
				e.printStackTrace();
			}
			//在本地生成文件
			File file = new File("E"+person1.getExpertNumber()+".doc");
			Writer writer = null;
			try {
				writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file) ,"utf-8"));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
			
				t.process(map, writer);  //将填充数据填入模板文件并输入到目标文件
				writer.close();  //关流
			} catch (TemplateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			//从服务器中下载并删除本地文件
			try {
				ExcelUtil.downLoad(request, file, response);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
		
		model.addAttribute("success", "下载成功！");
		
		return findPersonList(pageNo, new Person(), model, expertNumberId, request);
	}
	
	/**
	 * 批量下载专家
	 * @author dongli
	 * @date 2018年11月7日
	 * @param pid
	 * @param person
	 * @param request
	 * @param response
	 * @return 
	 * @return 
	 */
	@RequestMapping("downLoadPers")  
//	@ResponseBody
	public String downLoadPers(Person person, Model model,@RequestParam(defaultValue = "1") int pageNo, HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value = "expertNumberId", required = false) String expertNumberId,String number1,String number2){
		//提示用户先搜索
		if (StrUtil.isEmpty(person)) { //如果person为空，表示用户没有筛选
            model.addAttribute("searchEmpty", "至少需要一个搜索条件");
            return findPersonList(pageNo, person, model, expertNumberId, request);
        }
		/**
		 * 搜索专家
		 */
		//'E'+专家id来检索专家时，去除前缀操作
		String expertNum = "";
		// 重新复制客户id
		if (StringUtil.isNotEmpty(expertNumberId)) {
			expertNum = String.valueOf(expertNumberId.trim());
			// 去除字母
			expertNum = expertNum.replaceAll("[a-zA-Z]", "");
		}
		if (StringUtil.isNotEmpty(expertNum)) {
			person.setExpertNumber(Integer.parseInt(expertNum));
		}
        if (person.getTalentLevel() != null) {
        	String[] talentLevelArr = person.getTalentLevel().split(",");
        	person.setTalentLevelNumber(talentLevelArr.length);
        	person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
        }
        String[] researchFieldArr = null;
		if (StringUtil.isNotEmpty(person.getResearchField())) {
			researchFieldArr = person.getResearchField().split(",");
			person.setResearchFieldNumber(researchFieldArr.length);
			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
		}
		//从session中获取收集人（录入人）登录账号，存放在person中
//		person.setCollectPersonId(getUserId(request));
		
		//通过用户id查询专家的下载量
		UserDownPerson userDownPerson = new UserDownPerson();
		userDownPerson.setUserId(getUserId(request));
		userDownPerson.setDownTime(StrUtil.getCurrentDateTime("yyyy-MM-dd"));
		//查询用户当天下载的条数
		Integer integer = userDownPersonService.findCountByUser(userDownPerson);
		//通过用户id查询下载量（张三一天有200条下载量）
		Integer userDowns = userService.getById(getUserId(request)).getDownLoads();
		//如果库存量大于等于下载量
		if (userDowns <= integer) {
			model.addAttribute("max", "每天最多只能下载200条！");
			return findPersonList(pageNo, person, model, expertNumberId, request);
		}else {
			//库存量小于下载量
			Integer pers = userDowns - integer; //当前用户剩余的下载条数
			int pers1 = pers.intValue();
			//定义专家批量下载条数区间
			int num1 = Integer.parseInt(number1);
			int num2 = Integer.parseInt(number2);
			int num3 = num2 - num1;
			List<Person> list = new ArrayList<>();
			if (num1>=0 && num2>num1 && num3<=pers1) {
				person.setNumber1(num1);
				person.setNumber3(num3);
				list = personService.findMFPersonList(person);
			}else {
				model.addAttribute("cuowu", "第一个数填大于等于0的自然数，并且小于第二个数，两数之差不能大于200，剩余下载条数："+pers1+"条！");
				return findPersonList(pageNo, person, model, expertNumberId, request);
			}
			
			//一.下载专家
			//a.
			List<List<String>> personLists = Collections.synchronizedList(new ArrayList<List<String>>());
			//b.表头
			List<String> tagList = new ArrayList<>();
			tagList.add("专家ID");
			tagList.add("姓名");
			tagList.add("单位");
			tagList.add("职称");
			tagList.add("邮箱");
			tagList.add("手机");
			tagList.add("专业领域");
			tagList.add("人才类别");
			for (Person person1 : list) {
				List<String> content = new ArrayList<>();
				content.add("E"+person1.getExpertNumber());
				content.add(person1.getName());
				content.add(person1.getUnit());
				content.add(person1.getTitle());
				content.add(person1.getEmail());
				String tells = null;
				if (person1.getTell() != null && person1.getTell().length() >= 11) {
					tells = person1.getTell().substring(0, 3) + "****" + person1.getTell().substring(7, person1.getTell().length());
				}else {
					tells = person1.getTell();
				}
				content.add(tells);
				content.add(person1.getProfessionaField());
				if (person1.getTalentLevel() != null) {
					person1.setTalentLevel(getDicCheckboxWorth(person1.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
				}
				content.add(person1.getTalentLevel());
				
				//将多个list拼接成一个
				personLists.add(content);
			}
			//下载excel至服务器
			File file=ExcelUtil.writeExcel(tagList, personLists, "userDownPesonList.xls");
			try {
				//将服务器上文件下载至本地
				boolean b = ExcelUtil.downLoad1(request, file, response);
				//当本地下载成功时才能入库
				if (b) {
					//二.将专家存入数据库
					for (Person person2 : list) {
						UserDownPerson userDownPerson1 = new UserDownPerson();
						userDownPerson1.setPid(StrUtil.getUUID32());
						userDownPerson1.setUserId(getUserId(request));
						userDownPerson1.setPersonId(person2.getPid());  //应该是在循环中获取专家id
						userDownPerson1.setDownTime(StrUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss"));
						userDownPersonService.add(userDownPerson1);
					}
				}
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
		model.addAttribute("success", "下载成功！");
		return findPersonList(pageNo, person, model, expertNumberId, request);
	}
	
	/**
     * 转到需求匹配专家的页面
     * @author pdz
     * @date 2018年8月29日
     * @param model
     * @param demand
     * @return
     */
	@RequestMapping("/showDemandMatchedExpert")
    public String showDemandMatchedExpert(Model model, Demand demand,@RequestParam(value = "customerId", required = false) String customerId, HttpServletRequest request) {
		searchMatchedExpert(model, null, null, null, null, 1, demand.getPid(), request, customerId);
        return "demand/showDemandMatchedExpert";
    }
	
	
	/**
	 * 搜索要匹配的专家
	 * @author pdz
	 * @date 2018年8月29日
	 * @param pageNo
	 * @param person
	 * @param model
	 * @param expertNumberId
	 * @param demandId
	 * @param demand
	 * @return
	 */
    @RequestMapping("/searchMatchedExpert")
	public String searchMatchedExpert(Model model, String researchField, String area, String searchKeyword, Integer domesticOrForeign, @RequestParam(defaultValue = "1") int pageNo,
	        String demandId, HttpServletRequest request,@RequestParam(value="customerId", required=false) String customerId) {
		
		String researchFieldWorth = StringUtil.isEmpty(researchField) ? null : getDicCheckboxWorth(StrUtil.stringByByte(researchField).toString(), Constant.DICTIONTRY_DEMANDFIELD);
    	String areaWorth = StringUtil.isEmpty(area) ? null : getAreaWorth(area, domesticOrForeign);
    	Demand demand = demandService.getById(demandId);
    	demand.setDemandType(getDicCheckboxWorth(demand.getDemandType(), Constant.DICTIONTRY_DEMANDTYPE));
        Pagination pagination = new SolrOperation<>().queryList(pageNo, DEFAULT_COUNT, 7, demandId, researchFieldWorth, areaWorth, searchKeyword);
        ButtDetails buttDetails = new ButtDetails();
        buttDetails.setButtPersonId(getUserId(request));
        buttDetails.setDemandNumber(demandId);
        buttDetails.setFuture(1);
        buttDetails.setExpertNumberEmpty(false);
        List<ButtDetails> detailList = detailsService.findButtDetails(buttDetails);
        List<String> buttedExpertIdList = detailList.stream().map(ButtDetails::getExpertNumber).distinct().collect(Collectors.toList());
        String[] researchFieldArr = StringUtil.isNotEmpty(researchField) ? researchFieldArr = researchField.split(",") : new String[0];
        if (StringUtil.isNotEmpty(area))
            areaModel(model, area, domesticOrForeign);
        addListToModel(model);
        model.addAttribute("demand", demand);
        model.addAttribute("buttedExpertIdList", buttedExpertIdList);
        model.addAttribute("pageInfo", pagination);
        model.addAttribute("researchFieldArr", researchFieldArr);
        model.addAttribute("domesticOrForeign", domesticOrForeign);
        
        if (StringUtil.isNotEmpty(customerId)) {
        	Customer customer = customerService.getById(customerId);
        	model.addAttribute("customer", customer);
        	model.addAttribute("customerId", customerId);
        }
        return "demand/showDemandMatchedExpert";
	}
	
	/**
	 * 需求匹配专家
	 * @author pdz
	 * @date 2018年8月29日
	 * @param demandId 需求ID
	 * @param demand 里面有demandNumber和demandName
	 * @param expertId 这家id
	 * @param person 里面有expertNumber和name
	 * @param request
	 * @return
	 */
	@RequestMapping("/demandMatchExpert")
	@ResponseBody
	public String demandMatchExpert(String demandId, Demand demand, String expertId, Person expert, HttpServletRequest request) {
	    demand.setPid(demandId);
	    expert.setPid(expertId);
	    detailsService.addFirstButtDetails(null, demand, null, null, expert, getUserId(request));
	    return "success";
	}
	
	/**
	 * 从excel导入专家，修改为没有联系方式的不能导入
	 * @author pdz
	 * @date 2018年9月7日
	 * @param model
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping("/importPerson")
    public void importPerson(Model model, MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        if (file != null) {
            try(InputStream in = file.getInputStream()) {
                List<Person> importPersonList = ExcelUtil.readImportPersonList(in);
                String fullName = importPersonList.get(0).getCollectPersonName();
                User user = new User();
                user.setFullName(fullName);
                //收集人是同一个人才能这样
                String collectPersonId = userService.queryAll(user).get(0).getPid();
                List<String> tagList = Arrays.asList("专家ID", "姓名");
                List<List<String>> contentLists = new ArrayList<>();
                importPersonList.forEach(per -> importData(per, contentLists, collectPersonId, request));
                File excel = ExcelUtil.writeExcel(tagList, contentLists, "back.xls");
                ExcelUtil.downLoad(request, excel, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
	
    private void importData(Person person, List<List<String>> contentLists, String collectPersonId, HttpServletRequest request) {
        person.setPid(StrUtil.getUUID32());
        person.setCollectPersonId(collectPersonId);
        person.setEntryTime(StrUtil.getCurrentDateTime());
        person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
        if (StringUtil.isNotEmpty(person.getTalentLevel())) 
            person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
        if (hasContact(person)) {
        	personService.importData(person);
        	if (person.getExpertNumber() != null) {
        		List<String> list = Arrays.asList("E"+person.getExpertNumber().toString(), person.getName());
        		contentLists.add(list);
        	}
        }
    }
    
    @RequestMapping("/importUpdate")
    public String importUpdate(MultipartFile file) {
    	if (file != null) {
            try(InputStream in = file.getInputStream()) {
                List<Person> importPersonList = ExcelUtil.readImportUpdatePersonList(in, person -> personService.findMPersonList(person).get(0));
                importPersonList.forEach(per -> {
                	personService.update(per);
                	IsolrOperation<LucenePerson> isolrOperation = new SolrOperation<LucenePerson>();
            		//把Person转换为LucenePerson
            		LucenePerson lucenePerson = lucenePersonConversion(per);
            		isolrOperation.update("person", lucenePerson);
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    	return "redirect:/person/findPersonList";
    }
    

//    /* 日志输出 */
//    private final Logger logger = LoggerFactory.getLogger(PersonController.class);
//
//    @Resource 
//    private PersonService personService; 		 //专家
//    @Resource
//    private DictiontryService dictiontryService; //字典
//    @Resource
//    private ConferenceService conferenceService; //会议
//    @Resource
//    private DetailsService detailsService;       //详情
//    @Resource
//    private DemandService demandService;		 //需求
//    @Resource
//    private UserService userService;			 //用户
//    @Resource
//    private ConOfAttrService conOfAttrService;   //会议相关
//    
//    /**将常用的list封装到Model中*/
//    private void addListToModel(Model model){
//    	/**
//    	 * 用于修改页面的回显
//    	 */
//    	//项目来源
//        List<Dictiontry> projecSourcetDictiontryList = getProjectSorce();
//        //所有国家
//        List<Dictiontry> countryDictiontryList = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_COUNTRY);
//        //所有省份
//        List<Dictiontry> provinceDictiontryList = getAreaProvince();
//        //所属领域
//        List<Dictiontry> researchFieldDictiontryList = getResearchField();
//        //专家类型
//        List<Dictiontry> personTypeList = getPersonType();
//        //人才级别
//        List<Dictiontry> talentLevelListByDic = getTalentLevel();
//		/**
//		 * 用于显示对接详情添加页面的遍历
//		 */
//		//对接状态下拉列表
//		List<Dictiontry> buttStatus = getButtStatus();
//		/**
//		 * 匹配需求
//		 */
//		// 需求类型demandType
//        List<Dictiontry> demandTypeDictiontryList = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_DEMANDTYPE);
//        // 需求状态
//        List<Dictiontry> demandStatusDictiontryList = SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_DEMANDSTATUS);
//        // 专家类型
//        List<Dictiontry> personTypeDictiontryList = getPersonType();
//        // 人才级别
//        List<Dictiontry> talentLevelDictiontryList = getTalentLevel();
//
//        model.addAttribute("projecSourcetDictiontryList", projecSourcetDictiontryList);
//        model.addAttribute("provinceDictiontryList", provinceDictiontryList);
//        model.addAttribute("researchFieldDictiontryList", researchFieldDictiontryList);
//        model.addAttribute("personTypeList", personTypeList);
//        model.addAttribute("talentLevelListByDic", talentLevelListByDic);
//        model.addAttribute("buttStatus", buttStatus);
//        model.addAttribute("countryDictiontryList",countryDictiontryList );
//        model.addAttribute("demandTypeDictiontryList",demandTypeDictiontryList );
//        model.addAttribute("demandStatusDictiontryList",demandStatusDictiontryList );
//        model.addAttribute("personTypeDictiontryList",personTypeDictiontryList );
//        model.addAttribute("talentLevelDictiontryList",talentLevelDictiontryList );
//    }
//    
//    /**
//	 * 分页查询
//	 * @return 返回专家主页面
//	 */
//	@RequestMapping(value= "findPersonList",produces="application/json;charset=UTF-8")
//	public String findPersonList(Integer pageNo,Person person,Model model,
//			@RequestParam(value = "expertNumberId", required = false) String expertNumberId
//			){
//		//分页
//		if(null==pageNo){
//			pageNo=1;
//		}
//		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);
//		
//		//'E'+专家id来检索专家时，去除前缀操作
//		String expertNum = "";
//		// 重新复制客户id
//		if (StringUtil.isNotEmpty(expertNumberId)) {
//			expertNum = String.valueOf(expertNumberId.trim());
//			// 去除字母
//			expertNum = expertNum.replaceAll("[a-zA-Z]", "");
//		}
//		if (StringUtil.isNotEmpty(expertNum)) {
//			person.setExpertNumber(Integer.parseInt(expertNum));
//		}
//		
//        if (person.getTalentLevel() != null) {
//        	String[] talentLevelArr = person.getTalentLevel().split(",");
//        	person.setTalentLevelNumber(talentLevelArr.length);
//        	person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
//        	model.addAttribute("talentLevelArr",talentLevelArr );
//        }else {
//        	model.addAttribute("talentLevelArr","" );
//		}
//        
//        String[] researchFieldArr = null;
//		if (StringUtil.isNotEmpty(person.getResearchField())) {
//			researchFieldArr = person.getResearchField().split(",");
//			person.setResearchFieldNumber(researchFieldArr.length);
//			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
//		}
//		
//		//人才级别
//        List<Dictiontry> talentLevelListByDic = getTalentLevel();		
//		//模糊查询person表
//		List<Person> list = personService.findMPersonList(person);
//		//将list放进PageInfo
//		PageInfo<Person> pageInfo = new PageInfo<Person>(list);
//		//因为人才级别属非必填字段但是页面要展示该字段 ，所以在这里先判断是否为空然后进行遍历
//		pageInfo.getList().stream().filter(per -> StringUtil.isNotEmpty(per.getTalentLevel()))
//						.forEach(per -> per.setTalentLevel(getDictiontryWorth(per.getTalentLevel(), talentLevelListByDic)));
//		
//		if (person.getArea() != null){
//            areaModel(model, person.getArea(), person.getDomesticOrForeign());
//		}
//		
//		addListToModel(model);
//		model.addAttribute("pageInfo", pageInfo);
//		model.addAttribute("person", person);
//		model.addAttribute("researchFieldArr",researchFieldArr );
//		model.addAttribute("talentLevelListByDic",talentLevelListByDic );
//		
//		return "person";
//	}
//	
//	/**
//	 * 进入隐藏的专家管理页面
//	 * @author dongli
//	 * @date 2018年9月6日
//	 * @param person
//	 * @param model
//	 * @return
//	 */
//	@RequestMapping(value= "personHideList",produces="application/json;charset=UTF-8")
//	public String personHideList(Person person,Model model){
//		
//		PageInfo<Person> pageInfo = new PageInfo<Person>(new ArrayList<>());
//		
//		addListToModel(model);
//        model.addAttribute("pageInfo", pageInfo);
//        model.addAttribute("person", person);
//		return "person_hide";
//	}
//	
//	/**
//	 * 分页查询隐藏的专家管理页面
//	 * @author dongli
//	 * @date 2018年8月28日
//	 * @param pageNo
//	 * @param person
//	 * @param model
//	 * @param expertNumberId
//	 * @return
//	 */
//	@RequestMapping(value= "findPersonHideList",produces="application/json;charset=UTF-8")
//	public String findPersonHideList(Model model,@RequestParam(defaultValue = "1") int pageNo,Person person,
//			@RequestParam(value = "expertNumberId", required = false) String expertNumberId
//			){
//		if (StrUtil.isEmpty(person)) {
//            model.addAttribute("searchEmpty", "至少需要一个搜索条件");
//            return personHideList(person,model);
//        }
//		
//		//分页
//		PageHelper.startPage(pageNo, DEFAULT_COUNT);
//		
//		//'E'+专家id来检索专家时，去除前缀操作
//		String expertNum = "";
//		// 重新复制客户id
//		if (StringUtil.isNotEmpty(expertNumberId)) {
//			expertNum = String.valueOf(expertNumberId.trim());
//			// 去除字母
//			expertNum = expertNum.replaceAll("[a-zA-Z]", "");
//		}
//		if (StringUtil.isNotEmpty(expertNum)) {
//			person.setExpertNumber(Integer.parseInt(expertNum));
//		}
//		if (person.getTalentLevel() != null) {
//        	String[] talentLevelArr = person.getTalentLevel().split(",");
//        	person.setTalentLevelNumber(talentLevelArr.length);
//        	person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
//        	model.addAttribute("talentLevelArr",talentLevelArr );
//        }else {
//        	model.addAttribute("talentLevelArr","" );
//		}
//		
//		String[] researchFieldArr = null;
//		if (StringUtil.isNotEmpty(person.getResearchField())) {
//			researchFieldArr = person.getResearchField().split(",");
//			person.setResearchFieldNumber(researchFieldArr.length);
//			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
//		}
//		
//		//人才级别
//        List<Dictiontry> talentLevelListByDic = getTalentLevel();
//		//模糊查询person表
//		List<Person> list = personService.findMPersonList(person);
//		//将list放进PageInfo
//		PageInfo<Person> pageInfo = new PageInfo<Person>(list);
//		//因为人才级别属非必填字段但是页面要展示该字段 ，所以在这里先判断是否为空然后进行遍历
//		pageInfo.getList().stream().filter(per -> StringUtil.isNotEmpty(per.getTalentLevel()))
//						.forEach(per -> per.setTalentLevel(getDictiontryWorth(per.getTalentLevel(), talentLevelListByDic)));
//		
//		if (person.getArea() != null){
//            areaModel(model, person.getArea(), person.getDomesticOrForeign());
//		}
//		
//		addListToModel(model);
//		model.addAttribute("pageInfo", pageInfo);
//		model.addAttribute("person", person);
//		model.addAttribute("researchFieldArr",researchFieldArr );
//		model.addAttribute("talentLevelListByDic",talentLevelListByDic );
//		
//		return "person_hide";
//	}
//	
//	/**
//	 * 把Person转换为LucenePerson
//	 * @author dongli
//	 * @date 2018年9月21日
//	 * @param person
//	 * @return
//	 */
//	public LucenePerson lucenePersonConversion(Person person){
//		LucenePerson lp = new LucenePerson();
//		try{
//			//pid
//			String expertId = person.getPid();
//			if(expertId!=null&&!"".equals(expertId)){
//				lp.setExpertId(expertId);
//			}
//			//专家id
//			Integer expertNumber = person.getExpertNumber();
//			if(expertNumber!=null&&expertNumber>0){
//				lp.setExpertNumber("E"+expertNumber);
//			}
//			//专家来源
//			Integer source = person.getSource();
//			if(source!=null&&source>0){
//				lp.setSource(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
//			}
//			//专家类型
//			Integer type = person.getType();
//			if(type!=null && type>0){
//				lp.setType(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
//			}
//			/**
//			 * 所属领域
//			 */
//			String researchField = person.getResearchField();
//			if(researchField!=null &&!"".equals(researchField)){
//				researchField = getDicCheckboxWorth(person.getResearchFieldInteger().toString(), Constant.DICTIONTRY_PROJECTFIELD);
//				String[] arr  = researchField.split(",");
//				List<String> list = new ArrayList<String>();
//				for(String t :arr){
//					list.add(t);
//				}
//				lp.setResearchField(list);
//			}
//			//地区
//			String	area =person.getArea();
//			if(area!=null&&!"".equals(area)){
//				lp.setArea(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
//			}
//			/**
//			 * 人才级别
//			 */
//			String	talentLevel =person.getTalentLevel();
//			if(talentLevel!=null&&!"".equals(talentLevel)){
//				talentLevel = getDicCheckboxWorth(person.getTalentLevelInteger().toString(), Constant.DICTIONTRY_TALENTLEVEL);
//				String[] arr  = talentLevel.split(",");
//				List<String> list = new ArrayList<String>();
//				for(String t :arr){
//					list.add(t);
//				}
//				lp.setTalentLevel(list);
//			}
//			//姓名
//			String	name = person.getName();
//			if(name!=null&&!"".equals(name)){
//				lp.setName(name);
//			}
//			//毕业院校及所学专业
//			String	schoolAndMajor =person.getSchoolAndMajor();
//			if(schoolAndMajor!=null&&!"".equals(schoolAndMajor)){
//				lp.setSchoolAndMajor(schoolAndMajor);
//			}
//			//单位
//			String	unit = person.getUnit();
//			if(unit!=null&&!"".equals(unit)){
//				lp.setUnit(unit);
//			}
//			//职务(职称)
//			String	title = person.getTitle();
//			if(title!=null&&!"".equals(title)){
//				lp.setTitle(title);
//			}
//			//专业领域
//			String	professionaField =person.getProfessionaField();
//			if(professionaField!=null&&!"".equals(professionaField)){
//				lp.setProfessionaField(professionaField);
//			}
//			//教育背景
//			String	education =person.getEducation();
//			if(education!=null&&!"".equals(education)){
//				lp.setEducation(education);
//			}
//			//工作经历
//			String	workExp =person.getWorkExp();
//			if(workExp!=null&&!"".equals(workExp)){
//				lp.setWorkExp(workExp);
//			}
//			//荣誉奖励
//			String	honorAward =person.getHonorAward();
//			if(honorAward!=null&&!"".equals(honorAward)){
//				lp.setHonorAward(honorAward);
//			}
//			//科技成果
//			String	technica = person.getTechnica();
//			if(technica!=null&&!"".equals(technica)){
//				lp.setTechnica(technica);
//			}
//		}catch(Exception e){
//			e.printStackTrace();
//			return null;
//		}
//		return lp;
//	}
//	
//	/**
//	 * 进入添加页面
//	 * @return
//	 */
//	@RequestMapping(value= "addView",produces="application/json;charset=UTF-8")
//	public String addView(Model model){
//		//将person传递给前台
//		if(!model.containsAttribute("person")){
//			model.addAttribute("person", new Person());
//		}
//		if (!model.containsAttribute("researchFieldArr")) {
//			model.addAttribute("researchFieldArr", "");
//		}
//		if (!model.containsAttribute("talentLevelArr")) {
//			model.addAttribute("talentLevelArr", "");
//		}
//				
//		//调用本类方法
//		addListToModel(model);
//		return "personAdd";
//	}
//	
//	//提取添加页面回显的公共方法
//	public void addInfo(Person person,Model model){
//		// 获取地区相关数据，便于回显
//		String areaId = person.getArea();
//		String cityId = "";
//		String province = "";
//		if (StringUtil.isNotEmpty(areaId)) {
//			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
//				// 说明是区的id
//				// 截取得到省和市的id
//				cityId = areaId.substring(0, 5);
//				province = areaId.substring(0, 2);
//				model.addAttribute("areaId", areaId);
//				model.addAttribute("cityId", cityId);
//				model.addAttribute("province", province);
//			}
//			if (areaId.length() < 3 && areaId.length() > 0) {
//				// 说明是省的id
//				model.addAttribute("province", areaId);
//			}
//			if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
//				// 说明是市的id
//				// 截取得到省和市的id
//				cityId = areaId;
//				province = areaId.substring(0, 2);
//				model.addAttribute("province", province);
//				model.addAttribute("cityId", cityId);
//			}
//
//			// 所有市
//			List<Dictiontry> cityDictiontryList = getCityByProvince(province);
//			// 所有区
//			List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);
//
//			model.addAttribute("cityDictiontryList", cityDictiontryList);
//			model.addAttribute("areaDictiontryList", areaDictiontryList);
//		}
//
//		//回显所属领域
//		String[] researchFieldArr = null;
//		if (StringUtil.isNotEmpty(person.getResearchField())) {
//			researchFieldArr = person.getResearchField().split(",");
//		}
//		if (researchFieldArr != null) {
//			model.addAttribute("researchFieldArr", researchFieldArr);
//		} else {
//			model.addAttribute("researchFieldArr", "");
//		}
//		//回显人才级别
//		String[] talentLevelArr = null;
//		if (StringUtil.isNotEmpty(person.getTalentLevel())) {
//			talentLevelArr = person.getTalentLevel().split(",");
//		}
//		if (talentLevelArr != null) {
//			model.addAttribute("talentLevelArr", talentLevelArr);
//		} else {
//			model.addAttribute("talentLevelArr", "");
//		}
//
//		if(person.getDomesticOrForeign()!=null){
//			//国内外和省市区、国家名都不能为空
//			if (person.getDomesticOrForeign() == 1 && areaId != null) {
//				model.addAttribute("countryId", Integer.parseInt(areaId));
//			}
//		}
//		
//	}
//	
//	/**
//	 * 添加方法
//	 * @param person 
//	 * @return 专家的主页面
//	 * @throws IOException 
//	 */
//	@RequestMapping(value= "addPerson",method = RequestMethod.POST)
//	public String addPerson(@Valid Person person,BindingResult result,@RequestParam("annex1") MultipartFile annex1,
//			HttpServletRequest request,Model model) throws Exception{
//		//pid
//		person.setPid(StrUtil.getUUID32());
//		//收集人（录入人）
//		person.setCollectPersonId(getUserInfoBySession(request).getUserId());
//		//录入时间
//		person.setEntryTime(StrUtil.getCurrentDateTime());
//		//将所属领域复选框转换为二进制格式
//		if(StringUtil.isNotEmpty(person.getResearchField())){
//			person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
//		}
//		//将人才级别复选框转换为二进制格式
//		if(StringUtil.isNotEmpty(person.getTalentLevel())){
//			person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
//		}
//		
//		//上传附件
//		if (!annex1.isEmpty() && annex1 != null) {
//			// 文件名字
//			String fileName = annex1.getOriginalFilename();
//			String oldFileName = FileUtils.generateFileName("person", fileName);
//			person.setAnnex(oldFileName);
//			try {
//				FileUtils.uploadFile(annex1.getBytes(), Constant.DEF_PERSON_PATH, oldFileName);
//			} catch (Exception e) {
//				logger.error("上传文件失败：" + e.getMessage());
//			}
//		}
//		
//		// 表单验证逻辑
//		if (result.hasErrors()) {
//			List<FieldError> fieldErrors = result.getFieldErrors();
//			for (FieldError fieldError : fieldErrors) {
//				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
//				//调用本类方法
//				addInfo(person,model);
//				
//				//发生错误，直接return
//				model.addAttribute("person", person);
//				return addView(model);
//			}
//		}
//		
//		//专家入库条件:姓名+（固定电话、手机、邮箱、微信、其他联系方式）五种联系方式中的其中一种才可以入库
//		if (!person.getName().isEmpty() && (!person.getTell().isEmpty() || !person.getFixedPhone().isEmpty() || 
//			!person.getEmail().isEmpty() || !person.getWechat().isEmpty() || !person.getOtherContact().isEmpty())
//		){
//			//当数据库中可以通过姓名+任意一种联系方式查询出专家 就提示此人已存在
//			Person per = personService.findPersonByInfo(person);
//			if (per != null) {
//				model.addAttribute("info", "此人已存在！");
//				//调用本类方法
//				addInfo(person,model);
//				
//				model.addAttribute("person", person);
//				return addView(model);
//			}
//			personService.addPerson(person);
//			
//			/**
//			 * 更新索引
//			 */
//			//对象复制 person ==> lucenePerson
//			//BeanUtils.copyProperties(person, lucenePerson);
//			//创建isolrOperation接口对象指向其实现类 
//			IsolrOperation<LucenePerson> isolrOperation = new SolrOperation<LucenePerson>();
//			//把Person转换为LucenePerson
//			LucenePerson lucenePerson = lucenePersonConversion(person);
//			List<LucenePerson> list = new ArrayList<LucenePerson>();
//			list.add(lucenePerson);
//			isolrOperation.add("person", list);
//			
//		}else {
//			model.addAttribute("alert", "请至少填写一种联系方式！");
//			//调用本类方法
//			addInfo(person,model);
//			
//			model.addAttribute("person", person);
//			return addView(model);
//		}
//		
//		//通过重定向返回专家页面
//		return "redirect:/person/findPersonList";
//	}
//	
//	/**
//	 * 进入修改页面
//	 * @return
//	 */
//	@RequestMapping(value= "updateView",produces="application/json;charset=UTF-8")
//	public String updateView(@RequestParam("pid") String pid,Model model,@RequestParam(value = "origType", required = false) String origType,@RequestParam(value = "conferencePid", required = false) String conferencePid){
//		//调用本类方法
//		addListToModel(model);
//		
//		//通过pid查询专家表
//		Person person = personService.findPersonByPid(pid);
//		
//		String cityId = "";
//		String province = "";
//		String areaId = String.valueOf(person.getArea());
//		if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 9) {
//			// 说明是区的id
//			// 截取得到省和市的id
//			cityId = areaId.substring(0, 5);
//			province = areaId.substring(0, 2);
//			model.addAttribute("areaId", areaId);
//			model.addAttribute("cityId", cityId);
//			model.addAttribute("province", province);
//		}
//		if (areaId.length() < 3 && areaId.length() > 0) {
//			// 说明是省的id
//			model.addAttribute("province", areaId);
//		}
//		if (areaId.length() < 10 && areaId.length() > 4 && areaId.length() == 5) {
//			// 说明是市的id
//			// 截取得到省和市的id
//			cityId = areaId;
//			province = areaId.substring(0, 2);
//			model.addAttribute("province", province);
//			model.addAttribute("cityId", cityId);
//		}
//
//		if (person.getDomesticOrForeign() == 1) {
//			model.addAttribute("countryId", Integer.parseInt(areaId));
//		}
//		
//		// 所有省份
//		List<Dictiontry> provinceDictiontryList = getAreaProvince();
//		// 所有市
//		List<Dictiontry> cityDictiontryList = getCityByProvince(province);
//		// 所有区
//		List<Dictiontry> areaDictiontryList = getAreaByCity(cityId);
//		
//		// 所属领域二进制转化为字符串并存放到数组中
//		String[] researchFieldArr = StrUtil.byteToString(person.getResearchField()).split(",");
//		model.addAttribute("researchFieldArr", researchFieldArr);
//		// 人才级别二进制转化为字符串并存放到数组中
//		if (person.getTalentLevel() != null) {
//			String[] talentLevelFieldArr = StrUtil.byteToString(person.getTalentLevel()).split(",");
//			model.addAttribute("talentLevelFieldArr", talentLevelFieldArr);
//		}else {
//			model.addAttribute("talentLevelFieldArr", "");
//		}
//		
//		model.addAttribute("person",person);
//		model.addAttribute("provinceDictiontryList", provinceDictiontryList);
//		model.addAttribute("cityDictiontryList", cityDictiontryList);
//		model.addAttribute("areaDictiontryList", areaDictiontryList);
//		
//		model.addAttribute("origType", origType);
//		model.addAttribute("conferencePid", conferencePid);
//		
//		return "personUpdate";
//	}
//	
//	/**
//	 * 修改方法
//	 * @return
//	 */
//	@RequestMapping(value= "updatePerson",produces="application/json;charset=UTF-8",method = RequestMethod.POST)
//	public String updatePerson(@Valid Person person,BindingResult bindingResult,@RequestParam("annex1") MultipartFile annex1,
//			HttpServletRequest req,Model model,@RequestParam(value = "origType", required = false) String origType,@RequestParam(value = "conferencePid", required = false) String conferencePid){
//		//重新选择附件并上传
//		if (!annex1.isEmpty() && annex1 != null) {
//			// 文件名字
//			String fileName = annex1.getOriginalFilename();
//			String oldFileName = FileUtils.generateFileName("person", fileName);
//			person.setAnnex(oldFileName);
//			try {
//				FileUtils.uploadFile(annex1.getBytes(), Constant.DEF_PERSON_PATH, oldFileName);
//			} catch (Exception e) {
//				logger.error("上传文件失败：" + e.getMessage());
//			}
//		}else {
//			//当附件为空的时候不改变原来附件的内容
//			String fileName = FileUtils.transferTo(Constant.DEF_PERSON_PATH, annex1, "person");
//			Person per = personService.getById(person.getPid());
//			fileName = StringUtil.isEmpty(fileName) ? per.getAnnex() : fileName ;
//			person.setAnnex(fileName);
//		}
//		
//		//表单验证逻辑
//		if (bindingResult.hasErrors()) {
//			List<FieldError> fieldErrors = bindingResult.getFieldErrors();
//			for (FieldError fieldError : fieldErrors) {
//				logger.error("错误字段为：{},错误信息为：{}", fieldError.getField(), fieldError.getDefaultMessage());
//				// 发生错误，直接return
//				model.addAttribute("person", person);
//				return updateView(person.getPid(),model,null,null);
//			}
//		}
//		
//		// 转化为二进制保存
//		person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
//		if (person.getTalentLevel() != null) {
//			person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
//		}
//		
//		//专家入库条件:姓名+（固定电话、手机、邮箱、微信、其他联系方式）五种联系方式中的其中一种才可以入库
//		if (!hasContact(person)) {
//            model.addAttribute("alert", "至少填写一种联系方式");
//            return updateView(person.getPid(),model,null,null);
//        } else if (personService.updatePersonExists(person)) {
//        	model.addAttribute("info", "不能修改为已存在的专家");
//        	return updateView(person.getPid(),model,null,null);
//        }
//		personService.update(person);
//		
//		/**
//		 * 更新索引
//		 */
//		//创建isolrOperation接口对象指向其实现类 
//		IsolrOperation<LucenePerson> isolrOperation = new SolrOperation<LucenePerson>();
//		//把Person转换为LucenePerson
//		LucenePerson lucenePerson = lucenePersonConversion(person);
//		isolrOperation.update("person", lucenePerson);
//		
//		/*if (!person.getName().isEmpty() && (!person.getTell().isEmpty() || !person.getFixedPhone().isEmpty() || 
//			!person.getEmail().isEmpty() || !person.getWechat().isEmpty() || !person.getOtherContact().isEmpty())
//		){
//			Person person2 = personService.getById(person.getPid());
//			//判断当专家的姓名及联系方式同时发生改变的时候
//			if (!person.getName().equals(person2.getName()) && (!person.getTell().equals(person2.getTell()) || !person.getFixedPhone().equals(person2.getFixedPhone()) || 
//				!person.getEmail().equals(person2.getEmail()) || !person.getWechat().equals(person2.getWechat()) || !person.getOtherContact().equals(person2.getOtherContact()))
//			){
//				Person per = personService.findPersonByInfo(person);
//				if (per != null) {
//					model.addAttribute("info", "此人已存在！");
//					return updateView(person.getPid(),model);
//				}
//			}
//			personService.updatePerson(person);
//		}else {
//			model.addAttribute("alert", "请至少填写一种联系方式！");
//			return updateView(person.getPid(),model);
//		}*/
//		
//		//调用本类方法
//		addListToModel(model);
//		//通过重定向返回专家页面
//		if(StringUtil.isNotEmpty(origType)){
//			return "redirect:/conference/showDetail?conferenceId=" + conferencePid;
//		}else{
//			return "redirect:/person/findPersonList";
//		}
//	}
//	
//	/**
//	 * 进入专家匹配需求页面
//	 * @author dongli
//	 * @date 2018年8月27日
//	 * @param pid
//	 * @param model
//	 * @param pageNo
//	 * @return 
//	 */
//	@RequestMapping(value = "mateDemandView")
//	public String mateDemandView(Person person, Model model) {
//
//		PageInfo<Demand> pageInfo = new PageInfo<Demand>(new ArrayList<>());
//        addListToModel(model);
//        model.addAttribute(pageInfo);
//        model.addAttribute("person", person);
//
//		return "personOfDemandList";
//	}
//	
//	/**
//	 * 过滤已经匹配过的需求，使其不能再勾选，背景显示为隐藏色
//	 * @author dongli
//	 * @date 2018年8月30日
//	 * @param model
//	 * @param demand
//	 * @param searchKeyword
//	 * @param pageNo
//	 * @param personId
//	 * @param person
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("mateDemand")
//    public String mateDemand(Model model, Demand demand, String searchKeyword, @RequestParam(defaultValue = "1") int pageNo, 
//            String personId, Person person, HttpServletRequest request) {
//		
//		person.setPid(personId);
//		if (StringUtil.isEmpty(searchKeyword) && StrUtil.isEmpty(demand)) {
//            model.addAttribute("searchEmpty", "至少需要一个搜索条件");
//            return mateDemandView(person,model);
//        }
//        model.addAttribute("person", person);
//        
//        //查询并检索需求
//        PageInfo<Demand> searchPageInfo = searchPageInfo(model, demand, searchKeyword, pageNo);
//        //根据personId查询对接详情，然后筛选出已经对接过的demand
//        ButtDetails olderButt = new ButtDetails();
//        olderButt.setExpertNumber(personId);
//        olderButt.setButtPersonId(getUserId(request));
//        olderButt.setFuture(1);
//        List<String> searchDemandIdList = searchPageInfo.getList().stream().map(Demand::getPid).collect(Collectors.toList());
//        List<ButtDetails> historyButtDetails = detailsService.findHistoryButtDetails(olderButt);
//        List<String> buttedDemandIdList = historyButtDetails.stream().map(ButtDetails::getDemandNumber)
//            .filter(StringUtil::isNotEmpty).filter(demandId -> searchDemandIdList.contains(demandId)).collect(Collectors.toList());
//        model.addAttribute("buttedDemandIdList", buttedDemandIdList);
//        return "personOfDemandList";
//    }
//	
//	/**
//	 * 匹配需求
//	 * @author dongli
//	 * @date 2018年8月30日
//	 * @param demandId
//	 * @param demand
//	 * @param personId
//	 * @param person
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("pipei")
//    @ResponseBody
//    public String pipei(String demandId, Demand demand, String personId, Person person, HttpServletRequest request) {
//        demand.setPid(demandId);
//        person.setPid(personId);
//        detailsService.addFirstButtDetails(null, demand, null, null, person, getUserId(request));
//        return "success";
//    }
//	
//	/**
//	 * 专家匹配需求检索需求列表
//	 * @author dongli
//	 * @date 2018年8月30日
//	 * @param model
//	 * @param demand
//	 * @param searchKeyword
//	 * @param pageNo
//	 * @return
//	 */
//	private PageInfo<Demand> searchPageInfo(Model model, Demand demand, String searchKeyword, int pageNo) {
//        if (StringUtil.isEmpty(searchKeyword) && new Demand().equals(demand)) {//判断是否为空对象，不要往demand中的per属性中传值
//            return pageInfo(model, pageNo, demand);
//        }
//        if (StringUtil.isNotEmpty(searchKeyword)) {
//            if (searchKeyword.matches("D\\d{6,}"))
//                demand.setDemandNumber(Integer.parseInt(searchKeyword.replaceFirst("D", "")));
//            else
//                demand.setDemandName(searchKeyword);
//        }
//        String[] researchFieldArr = null;
//        String[] demandTypedArr = null;
//        if (StringUtil.isNotEmpty(demand.getDemandType())) {
//            demandTypedArr = demand.getDemandType().split(",");
//            demand.setDemandTypeNumber(demandTypedArr.length);
//            demand.setDemandTypeInteger(StrUtil.stringByByte(demand.getDemandType()));
//        }
//        if (StringUtil.isNotEmpty(demand.getResearchField())) {
//            researchFieldArr = demand.getResearchField().split(",");
//            demand.setResearchFieldNumber(researchFieldArr.length);
//            demand.setResearchFieldInteger(StrUtil.stringByByte(demand.getResearchField()));
//        }
//        PageInfo<Demand> pageInfo = pageInfo(model, pageNo, demand);
//        if (demand.getArea() != null)
//            areaModel(model, demand.getArea(), demand.getDomesticOrForeign());
//        model.addAttribute("searchKeyword", searchKeyword);
//        model.addAttribute("demand", demand);
//        model.addAttribute("researchFieldArr", researchFieldArr);
//        model.addAttribute("demandTypedArr", demandTypedArr);
//        return pageInfo;
//    }
//	
//	/**
//	 * 提取关于检索需求的公共方法pageInfo
//	 * @author dongli
//	 * @date 2018年8月30日
//	 * @param model
//	 * @param pageNo
//	 * @param dem
//	 * @return
//	 */
//	private PageInfo<Demand> pageInfo(Model model, int pageNo, Demand dem) {
//        PageHelper.startPage(pageNo, DEFAULT_COUNT);
//        List<Dictiontry> demandTypeDictiontryList = SystemGlobals.getInstance()
//                .getDictiontryMap(Constant.DICTIONTRY_DEMANDTYPE);
//        List<Dictiontry> demandStatusDictiontryList = SystemGlobals.getInstance()
//                .getDictiontryMap(Constant.DICTIONTRY_DEMANDSTATUS);
//        
//        List<Demand> list = demandService.queryAll(dem);
//        list.forEach(demand -> demand.setDemandType(getDictiontryWorth(demand.getDemandType(), demandTypeDictiontryList)));
//        list.forEach(demand -> demand.setDemandStatusWorth(demandStatusDictiontryList.stream()
//                    .filter(dsd -> dsd.getPid().equals(demand.getDemandStatus()))
//                    .map(Dictiontry::getWorth).findAny().orElse("")));
//
//        PageInfo<Demand> pageInfo = new PageInfo<Demand>(list);
//        addListToModel(model);
//        model.addAttribute(pageInfo);
//        return pageInfo;
//    }
//	
//	/**
//	 * 查看专家参会情况
//	 * @author dongli
//	 * @date 2018年8月24日
//	 * @param pid
//	 * @param model
//	 * @param conference
//	 * @param bindingResult
//	 * @param pageNum
//	 * @param conferenceNumberId
//	 * @return
//	 */
//	@RequestMapping(value= "mateConference")
//	public String mateConference(String pid,Person person, Model model,Conference conference, Integer pageNo,
//			@RequestParam(value = "conferenceNumberId", required = false) String conferenceNumberId){
//		
//		addListToModel(model);
//		String cityId = "";
//		String province = "";
//
//		if (StringUtil.isNotEmpty(conference.getArea()) && conference.getDomesticOrForeign()!=null) {
//			areaModel(model, conference.getArea(), conference.getDomesticOrForeign());
//		}
//		// 分页
//		if (null == pageNo) {
//			pageNo = 1;
//		}
//		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);
//
//		String conferenNum = "";
//		// 重新复制客户id
//		if (StringUtil.isNotEmpty(conferenceNumberId)) {
//			conferenNum = String.valueOf(conferenceNumberId.trim());
//			// 去除字母
//			conferenNum = conferenNum.replaceAll("[a-zA-Z]", "");
//		}
//		if (StringUtil.isNotEmpty(conferenNum)) {
//			conference.setConferenceNumber(Integer.parseInt(conferenNum));
//		}
//		if (StringUtil.isNotEmpty(conference.getConferenceName())) {
//			conference.setConferenceName(conference.getConferenceName().trim());
//		}
//		String[] researchFieldArr = null;
//		if (StringUtil.isNotEmpty(conference.getResearchField())) {
//			researchFieldArr = conference.getResearchField().split(",");
//			conference.setResearchFieldNumber(researchFieldArr.length);
//			conference.setResearchFieldInteger(StrUtil.stringByByte(conference.getResearchField()));
//		}
//		model.addAttribute("researchFieldArr", researchFieldArr);
//		
//		//创建一个空的list集合
//		List<Conference> conList1 = new ArrayList<>();
//		//通过专家的pid查询会议中间表
//		List<ConfOfAttr> list = conOfAttrService.findAttrByPersonId(pid);
//		//如果会议中间表中存在对应的数据
//		if (list != null) {
//			for (ConfOfAttr confOfAttr2 : list) {
//				conference.setPid(confOfAttr2.getConferenceId());
//				List<Conference> conList = conferenceService.findMConference(conference);
//				//将多个list拼接成一个
//				conList1.addAll(conList);
//			}
//		}
//		
//		for (int i = 0; i < conList1.size(); i++) {
//			String areaStr = "";
//			String reachName = "";
//			// 得到所属领域二进制
//			String rearch = conList1.get(i).getResearchField();
//			// 得到areaId
//			String areaIdStr = String.valueOf(conList1.get(i).getArea());
//			if (areaIdStr != null && !"".equals(areaIdStr) && !"null".equals(areaIdStr)) {
//				if (areaIdStr.length() == 4) {
//					// 说明是国外的
//					Dictiontry dicArea = new Dictiontry();
//					dicArea.setPid(Integer.parseInt(areaIdStr));
//					dicArea.setGroupName(Constant.DICTIONTRY_COUNTRY);
//					// 国外的名字
//					areaStr=getAreaWorth(areaIdStr, Constant.DICTIONTRY_COUNTRY);
//				}
//
//				if (areaIdStr.length() < 10 && areaIdStr.length() > 5) {
//					// 说明是区的id
//					// 截取得到省和市的id
//					Dictiontry dicArea = new Dictiontry();
//					dicArea.setNames(areaIdStr);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA);
//					areaStr=getAreaWorth(areaIdStr, 0);
//				}
//
//				if (areaIdStr.length() < 6 && areaIdStr.length() > 2 && areaIdStr.length() != 4) {
//					// 说明是市的id
//					Dictiontry dicArea = new Dictiontry();
//					cityId = areaIdStr.substring(0, 5);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA_CITY);
//					dicArea.setNames(cityId);
//					areaStr=getAreaWorth(areaIdStr, 0);
//				}
//
//				if (areaIdStr.length() < 3 && areaIdStr.length() > 0) {
//					// 说明是省的id
//					Dictiontry dicArea = new Dictiontry();
//					province = areaIdStr.substring(0, 2);
//					dicArea.setNames(province);
//					dicArea.setGroupName(Constant.DICTIONTRY_AREA_PROVINCE);
//					// 省的名字
//					areaStr=getAreaWorth(areaIdStr, 0);
//				}
//			}
//			// 给地区附上名字
//			conList1.get(i).setAreaNameStr(areaStr);
//			//取最右地区
//			if(areaStr.contains("-")){
//				String [] areaArray=areaStr.split("-");
//				String lastArea=areaArray[areaArray.length-1];
//				conList1.get(i).setAreaNameArray(lastArea);
//			}else{
//				conList1.get(i).setAreaNameArray(areaStr);
//			}
//
//			// 二进制转化为字符串
//			reachName=getDicCheckboxWorth(rearch, Constant.DICTIONTRY_PROJECTFIELD);
//			conList1.get(i).setResearchFieldNameStr(reachName);
//		}
//
//		// 将list放进PageInfo
//		PageInfo<Conference> pageInfo = new PageInfo<Conference>(conList1);
//		// 传至前台页面展示
//		model.addAttribute("pageInfo", pageInfo);
//		
//		return "personOfConferenceList";
//	}
//	
//	/**
//	 * 查看专家匹配需求详情
//	 * @author dongli
//	 * @date 2018年8月22日
//	 * @param model
//	 * @return
//	 */
//	@RequestMapping(value= "findButtDetailsList",produces="application/json;charset=UTF-8")
//	public String findButtDetailsList(String pid,Integer pageNo,HttpServletRequest request, ButtDetails buttDetails){
//		// 分页
//		if (null == pageNo) {
//			pageNo = 1;
//		}
//		PageHelper.startPage(pageNo, BaseController.DEFAULT_COUNT);
//		
//		// 将专家的pid封装到对接详情中
//		buttDetails.setExpertNumber(pid);;
//
//		buttDetails.setButtPersonId(getUserId(request));
//		buttDetails.setFuture(1);
//		buttDetails.setDemandNumberEmpty(false);
//		
//		//从缓存中获取对接状态
//		List<Dictiontry> buttStatus=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
//		List<ButtDetails> list = detailsService.findButtDetails(buttDetails);
//		//将list放进PageInfo
//		PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(list);
//		//通过pid查询专家
//		Person person = personService.findPersonByPid(pid);
//		
//		request.setAttribute("pageInfo", pageInfo);
//		request.setAttribute("buttStatus", buttStatus);
//		request.setAttribute("person", person);
//		
//		return "person_buttDemandDetails";
//	}
//	
//	/**
//	 * 下载详情附件
//	 * @author dongli
//	 * @date 2018年8月29日
//	 * @param request
//	 * @param response
//	 * @param fileName
//	 * @return
//	 */
//	@RequestMapping("download")
//	public String downloadFile(HttpServletRequest request, HttpServletResponse response,String fileName) {
//	 
//	    if (fileName != null) {
//	        //设置文件路径
//	        String realPath = Constant.DEF_BUT_DETAILS_PATH;
//	        File file = new File(realPath , fileName);
//	        if (file.exists()) {
//	            response.setContentType("application/force-download");// 设置强制下载不打开
//	            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
//	            byte[] buffer = new byte[1024];
//	            FileInputStream fis = null;
//	            BufferedInputStream bis = null;
//	            try {
//	                fis = new FileInputStream(file);
//	                bis = new BufferedInputStream(fis);
//	                OutputStream os = response.getOutputStream();
//	                int i = bis.read(buffer);
//	                while (i != -1) {
//	                    os.write(buffer, 0, i);
//	                    i = bis.read(buffer);
//	                }
//	                //System.out.println("success");
//	            } catch (Exception e) {
//	                e.printStackTrace();
//	            } finally {
//	                if (bis != null) {
//	                    try {
//	                        bis.close();
//	                    } catch (IOException e) {
//	                        e.printStackTrace();
//	                    }
//	                }
//	                if (fis != null) {
//	                    try {
//	                        fis.close();
//	                    } catch (IOException e) {
//	                        e.printStackTrace();
//	                    }
//	                }
//	            }
//	        }
//	    }
//	    return null;
//	}
//	
//	/**
//	 * 查看专家匹配的历史详情
//	 * @author dongli
//	 * @date 2018年8月29日
//	 * @param pageNo
//	 * @param buttdetails
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("findHistoryButtDetails")
//	public  String findHistoryButtDetails(Integer pageNo,String pid ,HttpServletRequest request){
//		try{
//			//从缓冲中获取对接状态
//			List<Dictiontry> buttStatus=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
//			request.setAttribute("buttStatus", buttStatus);
//			//通过对接详情pid查询对接详情
//			ButtDetails buttd= detailsService.findDetailsByPid(pid);
//			//分页
//			if(null==pageNo){
//				pageNo=1;
//			}
//			 PageHelper.startPage(pageNo, DEFAULT_COUNT);
//			 //将future设置为0，表示过期数据
//			 buttd.setFuture(0);
//			 //通过外键查询对接详情
//			 List <ButtDetails> listbutt = detailsService.findHistoryButtDetails(buttd);
//			 Person person = personService.findPersonByPid(buttd.getExpertNumber());
//			 
//			 PageInfo<ButtDetails> pageInfo = new PageInfo<ButtDetails>(listbutt);
//			 request.setAttribute("pageInfo", pageInfo);
//			 request.setAttribute("person", person);
//			 request.setAttribute("buttd", buttd);
//			 
//		}catch(Exception e){
//			logger.error( e.getMessage());
//		}
//		return "person_historyDetails";
//	}
//
//	/**
//	 * 进入添加对接详情页面
//	 * @author dongli
//	 * @date 2018年8月31日
//	 * @param pid
//	 * @param model
//	 * @return
//	 */
//	@RequestMapping(value = "addDetailsView",produces="application/json;charset=UTF-8")
//	public String addDetailsView(String pid,Model model){
//		//从缓存中获取对接状态
//		List<Dictiontry> buttStatus=SystemGlobals.getInstance().getDictiontryMap(Constant.DICTIONTRY_BUTTSTATUS);
//		//新建对接详情
//		ButtDetails buttDeteils = new ButtDetails();
//		model.addAttribute("buttDeteils", buttDeteils);
//		model.addAttribute("pid", pid);
//		model.addAttribute("buttStatus", buttStatus);
//		//通过pid查询对接详情
//		ButtDetails de =detailsService.findDetailsByPid(pid);
//		model.addAttribute("details",de.getButtDetails());
//		model.addAttribute("de", de);
//		//获取需求和专家
//		if (de != null) {
//			if(de.getDemandNumber()!=null&&!"".equals(de.getDemandNumber())){
//				Demand demand =demandService.getById(de.getDemandNumber());
//				model.addAttribute("demand", demand);
//			}
//			if(de.getExpertNumber()!=null&&!"".equals(de.getExpertNumber())){
//				Person person =personService.getById(de.getExpertNumber());
//				model.addAttribute("person", person);
//			}
//		}
//		
//		return "person_addDetailsView";
//	}
//	
//	/**
//	 * 添加对接详情
//	 * @author dongli
//	 * @date 2018年8月31日
//	 * @param buttDetails
//	 * @param bindingResult
//	 * @param pid
//	 * @param buttDetailsFiles
//	 * @param model
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping(value = "addDetails" , method = RequestMethod.POST)
//	public String addDetails(@Valid ButtDetails buttDetails, BindingResult bindingResult,String pid,
//			MultipartFile buttDetailsFiles, Model model, HttpServletRequest request){
//		//创建一个空的对象
//		ButtDetails oldButt = null;
//		try{
//			//通过pid查询对接详情
//			oldButt = detailsService.findDetailsByPid(pid);
//			//添加字段信息
//			buttDetails.setFuture(1);
//			buttDetails.setAddDateTime(StrUtil.getCurrentDateTime_two());
//			buttDetails.setButtPersonId(this.getUserId(request));
//			buttDetails.setButtName(this.getUserInfoBySession(request).getFullName());
//			//文件上传
//			if (null!=buttDetailsFiles && !buttDetailsFiles.isEmpty()) {
//				// 文件名字
//				String fileName = buttDetailsFiles.getOriginalFilename();
//				String oldFileName = FileUtils.generateFileName("buttdetails", fileName);
//				
//				buttDetails.setButtaNnex(oldFileName);
//				try {
//					FileUtils.uploadFile(buttDetailsFiles.getBytes(), Constant.DEF_BUT_DETAILS_PATH, oldFileName);
//				} catch (Exception e) {
//					logger.error("上传文件失败：" + e.getMessage());
//				}
//			}else {
//				//当附件为空的时候不改变原来附件的内容
//				String fileName = FileUtils.transferTo(Constant.DEF_BUT_DETAILS_PATH, buttDetailsFiles, "buttDetails");
//				ButtDetails butt = detailsService.findDetailsByPid(pid);
//				fileName = StringUtil.isEmpty(fileName) ? butt.getButtaNnex() : fileName ;
//				buttDetails.setButtaNnex(fileName);
//			}
//			//添加
//			detailsService.addButtDetails(oldButt,buttDetails);
//		}catch(Exception e){
//			logger.error( e.getMessage());
//		}
//		String expertNumber = oldButt.getExpertNumber();
//		//重定向到专家匹配需求页面
//		return "redirect:/person/findButtDetailsList?pid="+expertNumber;
//	}
//	
//	/**
//	 * 查看专家详情
//	 * @author dongli
//	 * @date 2018年8月23日
//	 * @param pid
//	 * @param model
//	 * @return
//	 */
//	@RequestMapping(value= "personDetails",produces="application/json;charset=UTF-8")
//	public String personDetails(@RequestParam("pid") String pid,Model model,Integer pageNo,HttpServletRequest request, ButtDetails buttDetails,
//			Person person,Conference conference,String conferenceNumberId){
//		//调用本类方法
//		addListToModel(model);
//		//通过pid查询专家表
//		Person per = personService.findPersonByPid(pid);
//		//通过pid查询用户
//		User user = userService.findUserById(per.getCollectPersonId());
//		
//		per.setSourceWorth(getDicSingleWorth(per.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
//		per.setTypeWorth(getDicSingleWorth(per.getType(), Constant.DICTIONTRY_PERSONTYPE));
//		per.setResearchField(getDicCheckboxWorth(per.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
//		if (per.getTalentLevel() != null) {
//			per.setTalentLevel(getDicCheckboxWorth(per.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
//		}
//		per.setAreaWorth(getAreaWorth(per.getArea(), per.getDomesticOrForeign()));
//		
//		//专家已匹配需求详情
//		buttDetails.setExpertNumber(pid);;
//		buttDetails.setButtPersonId(getUserId(request));
//		buttDetails.setFuture(1);
//		buttDetails.setDemandNumberEmpty(false);
//		List<ButtDetails> list = detailsService.findButtDetails(buttDetails);
//		//将list放进PageInfo1，避免和参会情况中的pageInfo发生冲突
//		PageInfo<ButtDetails> pageInfo1 = new PageInfo<ButtDetails>(list);
//		request.setAttribute("pageInfo1", pageInfo1);
//		
//		//专家参会情况
//		mateConference(pid,person,model,conference,pageNo,conferenceNumberId);
//		
//		//专家未匹配需求详情
//		SolrOperation<Person> solrOperation = new SolrOperation<Person>();
//		Pagination queryList = solrOperation.queryList(1, 10, 1, pid);
//		PageInfo<LuceneDemand> pageInfo2 = new PageInfo<LuceneDemand>(queryList.getList());
//		
//        //根据personId查询对接详情，然后筛选出已经对接过的demand
//        ButtDetails olderButt = new ButtDetails();
//        olderButt.setExpertNumber(pid);
//        olderButt.setButtPersonId(getUserId(request));
//        olderButt.setFuture(1);
//        List<String> searchDemandIdList = pageInfo2.getList().stream().map(LuceneDemand::getDemandId).collect(Collectors.toList());
//        List<ButtDetails> historyButtDetails = detailsService.findHistoryButtDetails(olderButt);
//        List<String> buttedDemandIdList = historyButtDetails.stream().map(ButtDetails::getDemandNumber)
//            .filter(StringUtil::isNotEmpty).filter(demandId -> searchDemandIdList.contains(demandId)).collect(Collectors.toList());
//        
//        model.addAttribute("buttedDemandIdList", buttedDemandIdList);
//		model.addAttribute("pageInfo2", pageInfo2);
//		model.addAttribute("person",per);
//		model.addAttribute("user",user);
//		
//		return "personDetails";
//	}
//	
//	//查看专家详情测试版
//	@RequestMapping(value= "personDetailsTest",produces="application/json;charset=UTF-8")
//	public String personDetailsTest(@RequestParam("pid") String pid,Model model){
//		//调用本类方法
//		addListToModel(model);
//		//通过pid查询专家表
//		Person person = personService.findPersonByPid("66f6aa26d9414064a90d53eac77af150");
//		//通过pid查询用户
//		User user = userService.findUserById(person.getCollectPersonId());
//		
//		person.setSourceWorth(getDicSingleWorth(person.getSource(), Constant.DICTIONTRY_PROJECTSOURCE));
//		person.setTypeWorth(getDicSingleWorth(person.getType(), Constant.DICTIONTRY_PERSONTYPE));
//		person.setResearchField(getDicCheckboxWorth(person.getResearchField(), Constant.DICTIONTRY_PROJECTFIELD));
//		if (person.getTalentLevel() != null) {
//			person.setTalentLevel(getDicCheckboxWorth(person.getTalentLevel(), Constant.DICTIONTRY_TALENTLEVEL));
//		}
//		person.setAreaWorth(getAreaWorth(person.getArea(), person.getDomesticOrForeign()));
//		
//		model.addAttribute("person",person);
//		model.addAttribute("user",user);
//		
//		return "personDetails1";
//	}
//	
//	/**
//	 * 下载专家附件
//	 * @author dongli
//	 * @date 2018年9月10日
//	 * @param request
//	 * @param response
//	 * @param fileName
//	 * @return
//	 */
//	@RequestMapping("downloadPerson")
//	public String downloadPersonFile(HttpServletRequest request, HttpServletResponse response,String fileName) {
//	 
//	    if (fileName != null) {
//	        //设置文件路径
//	        String realPath = Constant.DEF_PERSON_PATH;
//	        File file = new File(realPath , fileName);
//	        if (file.exists()) {
//	            response.setContentType("application/force-download");// 设置强制下载不打开
//	            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
//	            byte[] buffer = new byte[1024];
//	            FileInputStream fis = null;
//	            BufferedInputStream bis = null;
//	            try {
//	                fis = new FileInputStream(file);
//	                bis = new BufferedInputStream(fis);
//	                OutputStream os = response.getOutputStream();
//	                int i = bis.read(buffer);
//	                while (i != -1) {
//	                    os.write(buffer, 0, i);
//	                    i = bis.read(buffer);
//	                }
//	                System.out.println("success");
//	            } catch (Exception e) {
//	                e.printStackTrace();
//	            } finally {
//	                if (bis != null) {
//	                    try {
//	                        bis.close();
//	                    } catch (IOException e) {
//	                        e.printStackTrace();
//	                    }
//	                }
//	                if (fis != null) {
//	                    try {
//	                        fis.close();
//	                    } catch (IOException e) {
//	                        e.printStackTrace();
//	                    }
//	                }
//	            }
//	        }
//	    }
//	    return null;
//	}
//	
//	/**
//     * 转到需求匹配专家的页面
//     * @author pdz
//     * @date 2018年8月29日
//     * @param model
//     * @param demand
//     * @return
//     */
//	@RequestMapping("/showDemandMatchedExpert")
//    public String showDemandMatchedExpert(Model model, Demand demand) {
//	    PageInfo<Person> pageInfo = new PageInfo<Person>(new ArrayList<>());
//        addListToModel(model);
//        model.addAttribute(pageInfo);
//        model.addAttribute("demand", demand);
//        model.addAttribute("person", new Person());
//        return "demand/showDemandMatchedExpert";
//    }
//	
//	/**
//	 * 搜索要匹配的专家
//	 * @author pdz
//	 * @date 2018年8月29日
//	 * @param pageNo
//	 * @param person
//	 * @param model
//	 * @param expertNumberId
//	 * @param demandId
//	 * @param demand
//	 * @return
//	 */
//	@SuppressWarnings("unchecked")
//    @RequestMapping("/searchMatchedExpert")
//	public String searchMatchedExpert(@RequestParam(defaultValue = "1") Integer pageNo, Person person, Model model, String expertNumberId,
//	        String demandId, Demand demand, HttpServletRequest request) {
//	    demand.setPid(demandId);
//	    if (StringUtil.isEmpty(expertNumberId) && StrUtil.isEmpty(person)) {
//            model.addAttribute("searchEmpty", "至少需要一个搜索条件");
//            return showDemandMatchedExpert(model, demand);
//        }
//        model.addAttribute("demand", demand);
//        findPersonList(pageNo, person, model, expertNumberId);
//        //根据demandid查询对接详情，然后筛选出已经对接过的专家
//        ButtDetails olderButt = new ButtDetails();
//        olderButt.setDemandNumber(demandId);
//        olderButt.setButtPersonId(getUserId(request));
//        olderButt.setFuture(1);
//        List<ButtDetails> historyButtDetails = detailsService.findHistoryButtDetails(olderButt);
//        PageInfo<Person> pageInfo = (PageInfo<Person>) model.asMap().get("pageInfo");
//        List<String> searchExpertIdList = pageInfo.getList().stream().map(Person::getPid).collect(Collectors.toList());
//        List<String> buttedExpertIdList = historyButtDetails.stream().map(ButtDetails::getExpertNumber)
//            .filter(StringUtil::isNotEmpty).filter(experId -> searchExpertIdList.contains(experId)).collect(Collectors.toList());
//        model.addAttribute("buttedExpertIdList", buttedExpertIdList);
//        return "demand/showDemandMatchedExpert";
//	}
//	
//	/**
//	 * 需求匹配专家
//	 * @author pdz
//	 * @date 2018年8月29日
//	 * @param demandId 需求ID
//	 * @param demand 里面有demandNumber和demandName
//	 * @param expertId 这家id
//	 * @param person 里面有expertNumber和name
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("/demandMatchExpert")
//	@ResponseBody
//	public String demandMatchExpert(String demandId, Demand demand, String expertId, Person expert, HttpServletRequest request) {
//	    demand.setPid(demandId);
//	    expert.setPid(expertId);
//	    detailsService.addFirstButtDetails(null, demand, null, null, expert, getUserId(request));
//	    return "success";
//	}
//	
//	/**
//	 * 从excel导入专家，修改为没有联系方式的不能导入
//	 * @author pdz
//	 * @date 2018年9月7日
//	 * @param model
//	 * @param file
//	 * @param request
//	 * @return
//	 */
//	@RequestMapping("/importPerson")
//    public String importPerson(Model model, MultipartFile file, HttpServletRequest request) {
//        if (file != null) {
//            try(InputStream in = file.getInputStream()) {
//                List<Person> importPersonList = ExcelUtil.readImportPersonList(in);
//                importPersonList.forEach(per -> importData(per, request));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        return "redirect:/person/findPersonList";
//    }
//	
//    private void importData(Person person, HttpServletRequest request) {
//        person.setPid(StrUtil.getUUID32());
//        person.setCollectPersonId(getUserInfoBySession(request).getUserId());
//        person.setEntryTime(StrUtil.getCurrentDateTime());
//        person.setResearchFieldInteger(StrUtil.stringByByte(person.getResearchField()));
//        if (StringUtil.isNotEmpty(person.getTalentLevel())) 
//            person.setTalentLevelInteger(StrUtil.stringByByte(person.getTalentLevel()));
//        if (hasContact(person))
//            personService.importData(person);
//    }
    
    @RequestMapping("/checkName")
    @ResponseBody
    public List<Person> checkName(String name) {
    	List<Person> personList = personService.findMPersonList(new Person(name));
    	return personList;
    }

    @RequestMapping("/detailStatistics")
	public String detailStatistics(String beginDate, String endDate, String userId, @RequestParam(defaultValue="1") Integer pageNo, Model model) {
		PageHelper.startPage(pageNo, DEFAULT_COUNT);
		List<Person> list = personService.detailStatistics(beginDate, endDate, userId);
		PageInfo<Person> pageInfo = new PageInfo<>(list);
		List<User> userList = userService.queryInPidList(pageInfo.getList().stream().map(Person::getCollectPersonId).distinct().collect(Collectors.toList()));
		pageInfo.getList().forEach(per -> per.setCollectPersonId(userList.stream().filter(user -> per.getCollectPersonId().equals(user.getPid())).map(User::getFullName).findAny().get()));
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("pageInfo_person", true);
		model.addAttribute("route", "/person");
		return "detailStatistics";
	}
    
    @RequestMapping("/updateDetailStatistics")
    public String updateDetailStatistics(String beginDate, String endDate, String userId, Integer operaIndex, String fullname, @RequestParam(defaultValue="1") Integer pageNo, Model model) {
    	List<String> refPidList = queryUpdateLog(beginDate, endDate, userId, operaIndex);
    	PageHelper.startPage(pageNo, DEFAULT_COUNT);
		List<Person> list = personService.queryInPidList(refPidList);
		PageInfo<Person> pageInfo = new PageInfo<>(list);
		pageInfo.getList().forEach(per -> per.setCollectPersonId(fullname));
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("pageInfo_person", true);
		model.addAttribute("route", "/person");
		return "detailStatistics";
    }
}